今天忙着写简历,好累啊,希望可以拿到不错的offer!废话不多说还是更完这篇string methods, 绝不拖更!
横向对比一下
String.slice( begin [, end ] )
str.substring(indexStart[, indexEnd])
String.substr( start [, length ] )
对于这三个,第二个参数都是可选的。如果不选就从当前的index一直截取到末尾。
slice() 和 substring()
两个非常相似,仅有一点点不同。
- 如果start和end相等,不截取
- 如果只传入一个参数,一直截取到末尾
- 如果任一参数超过了字符串长度,将默认使用字符串长度
- 截取长度都不包括最后一个索引,str.slice(1, 4) 提取新字符串从第二个字符到第四个 (字符索引值为 1, 2, 和 3)。
区别substring():
If indexStart is greater than indexEnd, then the effect of substring() is as if the two arguments were swapped; for example, str.substring(1, 0) == str.substring(0, 1).
- 使用Substring如果第一个参数超过了第二个参数,将会互换。
- 如果Substring接受了NaN或者负数,会被自动转为0。
区别slice():
- 如果start > stop,slice()不会交换2个参数。
- 如果start接受了负数,就会从末尾开始取值
- 如果stop接受的负数,会停在string的长度减去stop的绝对值。
1
2
3
4var str = 'The morning is upon us.';
str.slice(-3); // returns 'us.' 从末尾取3个值`us.`
str.slice(-3, -1); // returns 'us'
str.slice(0, -1); // returns 'The morning is upon us' 长度减去1,停在了S,所以去了最后的 点
substr()
这个区别就比较明显了,substr第二个参数接受的是长度而非索引,其他规则都比较类似:
- 如果 start 为正值,且大于或等于字符串的长度,则 substr 返回一个空字符串。
- 如果 start 为负值,则 substr 把它作为从字符串末尾开始的一个字符索引。
感谢各位阅读!(鞠躬