JS中 String.prototype.slice、String.prototype.substring、String.prototype.substr 的区别

本文深入解析JavaScript中的三种字符串处理方法:slice、substring和substr。详细介绍了它们的参数、使用场景及区别,帮助开发者更准确地掌握字符串操作技巧。

String.prototype.slice

str.slice(beginSlice[, endSlice]) 方法提取一个字符串的一部分,并返回一新的字符串 MDN

  • beginSlice
    从该索引(以 0 为基数)处开始提取原字符串中的字符。如果值为负数,会被当做 sourceLength + beginSlice 看待,这里的sourceLength 是字符串的长度 (例如, 如果beginSlice 是 -3 则看作是: sourceLength - 3)
  • endSlice
    可选。在该索引(以 0 为基数)处结束提取字符串。如果省略该参数,slice会一直提取到字符串末尾。如果该参数为负数,则被看作是 sourceLength + endSlice,这里的 sourceLength 就是字符串的长度(例如,如果 endSlice 是 -3,则是, sourceLength - 3)。
var str = 'The morning is upon us.';
str.slice(-3);     // returns 'us.'
str.slice(-3, -1); // returns 'us'
str.slice(0, -1);  // returns 'The morning is upon us'

String.prototype.substring

str.substring(indexStart[, indexEnd]) 方法返回一个字符串在开始索引到结束索引之间的一个子集, 或从开始索引直到字符串的末尾的一个子集 MDN

  • indexStart
    需要截取的第一个字符的索引,该字符作为返回的字符串的首字母。
  • indexEnd
    可选。一个 0 到字符串长度之间的整数,以该数字为索引的字符不包含在截取的字符串内。

如果 indexStart 等于 indexEnd,substring 返回一个空字符串。
如果省略 indexEnd,substring 提取字符一直到字符串末尾。
如果任一参数小于 0 或为 NaN,则被当作 0。
如果任一参数大于 stringName.length,则被当作 stringName.length。
如果 indexStart 大于 indexEnd,则 substring 的执行效果就像两个参数调换了一样

不同点

  • substring 只要有负值,就会当做0
  • substring 第一个参数大于第二个,则两个参数位置互换

String.prototype.substr(not recommend)

str.substr(start[, length]) 返回一个字符串中从指定位置开始到指定字符数的字符 MDN

substr 从 start 位置开始提取字符,提取 length 个字符(或直到字符串的末尾)。
如果 start 为正值,且大于或等于字符串的长度,则 substr 返回一个空字符串。
如果 start 为负值,则 substr 把它作为从字符串末尾开始的一个字符索引。如果 start 为负值且 abs(start) 大于字符串的长度,则 substr 使用 0 作为开始提取的索引。注意负的 start 参数不被 Microsoft JScript 所支持。

var str = "abcdefghij";

console.log("(1,2): "    + str.substr(1,2));   // (1,2): bc
console.log("(-3,2): "   + str.substr(-3,2));  // (-3,2): hi
console.log("(-3): "     + str.substr(-3));    // (-3): hij
console.log("(1): "      + str.substr(1));     // (1): bcdefghij
console.log("(-20, 2): " + str.substr(-20,2)); // (-20, 2): ab
console.log("(20, 2): "  + str.substr(20,2));  // (20, 2):
console.log("(-111, 2): "  + str.substr(-111, 2));  // (20, 2): ab

不同点

  • substr 第二个参数表示截取的字符长度,不是截取的字符的位置

关注公众号 止水聊技术,即送技术资料,您的支持是我最大的动力
lxfriday_xyz

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值