var str = "qwertyuiop";
1、substring()方法:返回一个索引和另一个索引之间的字符串。
语法:str.substring(startIndex,endIndex);
Notice:↓↓↓↓↓↓↓↓↓↓
- substring() 提取字符串从 startIndex 开始到 endIndex,可以不包含 endIndex。
- 如果 startIndex 等于 endIndex,substring()则返回一个空字符串。
- 如果 endIndex 省略,则将 substring() 字符提取到字符串的末尾。
- 如果任一参数小于0或是NaN,它被视为为0。
- 如果任何一个参数都大于 str.length,则被视为是 str.length。
- 如果 startIndex 于 endIndex,那么效果substring()就好像这两个论点被交换了一样; 例如,str.substring(1, 0) == str.substring(0, 1)
例: console.log('(1, 2): ' + str.substring(1, 2)); // '(1, 2): w'
console.log('(1, 1): ' + str.substring(1, 1)); // '(1, 1): '
console.log('(1): ' + str.substring(1)); // '(1): wertyuiop'
console.log('(-3, 2): ' + str.substring(-3, 2)); // '(-3, 2): qw'
console.log('(-3): ' + str.substring(-3)); // '(-3): qwertyuiop'
console.log('(2, 20): ' + str.substring(2, 20)); // '(2, 20): ertyuiop'
console.log('(20, 2): ' + str.substring(20, 2)); // '(20, 2): ertyuiop'
2、substr()方法:返回从指定位置开始的字符串中指定字符数的字符。
语法:str.substr(startIndex,[strLength]);
Notice:↓↓↓↓↓↓↓↓↓↓
- substr() 会从 startIndex 获取长度为 strLength 字符(如果截取到字符串的末尾,则会停止截取)。
- 如果 startIndex 是正的并且大于或等于字符串的长度,则substr() 返回一个空字符串。
- 若 startIndex 为负数,则将该值加上字符串长度后再进行计算(如果加上字符串的长度后还是负数,则从0开始截取)。
- 如果 strLength 为0或为负数,substr() 返回一个空字符串。如果 strLength 省略,则将 substr() 字符提取到字符串的末尾。
例: console.log('(1, 2): ' + str.substr(1, 2)); // '(1, 2): we'
console.log('(1, 22): ' + str.substr(1, 22)); // '(1, 22): wertyuiop'
console.log('(20, 2): ' + str.substr(20, 2)); // '(20, 2): '
console.log('(-3, 2): ' + str.substr(-3, 2)); // '(-3, 2): io'
console.log('(-20, 2): ' + str.substr(-20, 2)); // '(-20, 2): qw'
console.log('(2, 0): ' + str.substr(2, 0)); // '(2, 0): '
console.log('(2, -3): ' + str.substr(2, -3)); // '(2, -3): '
console.log('(1): ' + str.substr(1)); // '(1): wertyuiop'
3、slice()方法:返回一个索引和另一个索引之间的字符串。
语法:str.slice(startIndex, endIndex);
Notice:↓↓↓↓↓↓↓↓↓↓
- 若 startIndex 为负数,则将该值加上字符串长度后再进行计算(如果加上字符串的长度后还是负数,则从0开始截取)。
- 如果 startIndex 大于或等于字符串的长度,则 slice() 返回一个空字符串。
- 如果 endIndex 省略,则将 slice() 字符提取到字符串的末尾。如果为负,它被视为 strLength
+endIndex 其中strLength是字符串的长度。
例: console.log('(-3, 9): ' + str.slice(-3, 9)); // '(-3, 9): io'
console.log('(-20, 2): ' + str.slice(-20, 2)); // '(-20, 2): qw'
console.log('(20, 2): ' + str.slice(20, 2)); // '(20, 2): '
console.log('(1): ' + str.slice(1)); // '(1): wertyuiop'
console.log('(0,-1): ' + str.slice(0,-1)); // '(0,-1): qwertyuio'

2万+

被折叠的 条评论
为什么被折叠?



