功能:返回一个索引和另外一个索引之间的字符串
语法:str.substring(start,[end])
注意:
- 截取范围包括start但是不包括end
- 若start==end,则返回空
- end可省略,如果省略则表示从start截取到字符串末尾
- 若某个参数是NaN或者小于0,那么等效为0;若某个参数大于字符串长,那么等效为字符串长
- 若start大于end,那么start和end交换,比如str.substring(2,0) == str.substring(0,2)
demo:
var str = 'abcdefghij';
console.log('(1, 2): ' + str.substring(1, 2)); // '(1, 2): b'
console.log('(1, 1): ' + str.substring(1, 1)); // '(1, 1): '
console.log('(-3, 2): ' + str.substring(-3, 2)); // '(-3, 2): ab'
console.log('(-3): ' + str.substring(-3)); // '(-3): abcdefghij'
console.log('(1): ' + str.substring(1)); // '(1): bcdefghij'
console.log('(-20, 2): ' + str.substring(-20, 2)); // '(-20, 2): ab'
console.log('(2, 20): ' + str.substring(2, 20)); // '(2, 20): cdefghij'
console.log('(20, 2): ' + str.substring(20, 2)); // '(20, 2): cdefghij'
功能:返回从指定位置开始的字符串中指定字符数的字符串
语法:str.substr(start,[length])
注意:
- 它会从start位置截取长度为length的字符串
- 若start是正数且大于或等于字符串长度,则返回一个空字符串
- 若start为负数,则将该值加上字符串长度再进行计算,若还是负数,则从0开始截取(实际上就是倒过来从尾部开始截取)
- 若length为0或负数,则返回空;若length省略,则截取到末尾
demo:
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): '
功能:返回一个索引到另一个索引间的字符串
语法:str.slice(start,[end])
注意:
- start和end都为正数时,截取范围不包括start和end
- 若start为负数,start=start+length,若还是负数,则从0开始截取(实际上就是倒过来从尾部开始截取)
- 若start大于或等于字符串长,则返回空
- 若end省略,则截取到字符串末尾;若end为负数,则end=length+end
demo:
var str = 'abcdefghij';
console.log('(1, 2): ' + str.slice(1, 2)); // '(1, 2): b'
console.log('(-3, 2): ' + str.slice(-3, 2)); // '(-3, 2): '
console.log('(-3, 9): ' + str.slice(-3, 9)); // '(-3, 9): hi'
console.log('(-3): ' + str.slice(-3)); // '(-3): hij'
console.log('(-3,-1): ' + str.slice(-3,-1)); // '(-3,-1): hi'
console.log('(0,-1): ' + str.slice(0,-1)); // '(0,-1): abcdefghi'
console.log('(1): ' + str.slice(1)); // '(1): bcdefghij'
console.log('(-20, 2): ' + str.slice(-20, 2)); // '(-20, 2): ab'
console.log('(20): ' + str.slice(20)); // '(20): '
console.log('(20, 2): ' + str.slice(20, 2)); // '(20, 2): '
补充:
split是将一个字符串分割为字符串数组
demo:
"hello".split("") //可返回 ["h", "e", "l", "l", "o"]
"2:3:4:5".split(":") //将返回["2", "3", "4", "5"]
参考:
[掘金-JS字符串截取函数slice(),substring(),substr()的区别](https://juejin.im/post/59e2af3151882578cf573319)