一、slice()和substring()都有两个参数start和end ,获取字符串从start(包含)到end(不包含)位置的字符
不过start和end都不是必填的(不填:start默认为0,end默认为字符串长度length),参数个数不同具体对应情况如下:
注:字符串的索引是从0到length-1
1.如果不写参数表示返回当前字符串(截取全部),start为0,end为字符串长度length;
var test_string = "hello world",
length = test_string.length;
test_string.slice() // "hello world"
test_string.substring() // "hello world"
等同于:
test_string.slice(0,length) // "hello world"
test_string.substring(0,length) // "hello world"
2.如果只有一个参数,则该参数为start值,end默认为字符串长度length;
var test_string = "hello world",
length = test_string.length;
test_string.slice(7) // "orld"
test_string.substring(7) // "orld"
等同于:
test_string.slice(7,length) // "orld"
test_string.substring(7,length) // "orld"
3.有两个参数,从start到end
var test_string = "hello world",
length = test_string.length;
test_string.slice(1,5) // "ello"
test_string.substring(1,5) // "ello"
二、substr()有两个参数start和n ,获取字符串从start(包含)位置开始的n个字符
1.如果不写参数表示返回当前字符串(截取全部),start为0,n为字符串长度length;
var test_string = "hello world",
length = test_string.length;
test_string.substr() // "hello world"
等同于:
test_string.substr(0,length) // "hello world"
2.如果只有一个参数,则该参数为start值,n默认为字符串长度length-start;
var test_string = "hello world",
length = test_string.length;
test_string.substr(7) // "orld"
等同于:
test_string.substr(7,length-7) // "orld"
3.有两个参数,从start开始的n个字符,如果n大于剩余字符串长度,在截取字符串的时候n被设置为 length-start
var test_string = "hello world",
length = test_string.length;
test_string.substr(7,4) // "orld"
当n的值大于剩余字符串长度时(这里剩余字符串长度为4):
test_string.substr(7,10) // "orld"
等同于:
test_string.substr(7,length-7) // "orld"
三、非正常情况,参数为负、start>end、start>length等
1.slice
var test_string = "hello world",
length = test_string.length;
1.当start>length
test_string.slice(12) // ""
test_string.slice(12,2) // ""
test_string.slice(12,-2) // ""
2.start>end
test_string.slice(5,2) // ""
3.start<0
test_string.slice(-1,2) // ""
test_string.slice(-4) // "orld"
等同于:
test_string.slice(length-4,length) // "orld"
4.end<0 end重置为length+end
test_string.slice(7,-1) // "orl"
等同于:
test_string.slice(7,length-1) // "orl"
综上,只有一个负参数表示获取最后几位,第二位为负表示获取start到length+end(end为负)之间的字符,其他为空字符串
2.substring
var test_string = "hello world",
length = test_string.length;
1.当start>length
test_string.substring(12) // ""
test_string.substring(12,2) // "llo world",原因见2
test_string.substring(12,-2) // "hello world",原因见2和3
2.start>end, start和end值被互换
test_string.substring(5,2) // "llo"
等同于:
test_string.substring(2,5) // "llo"
3.start<0, start被重置为0
test_string.substring(-1,2) // "he"
等同于:
test_string.substring(0,2) // "he"
test_string.substring(-4) // "hello world"
等同于:
test_string.substring(0,length) // "hello world"
3.substr
var test_string = "hello world",
length = test_string.length;
1.start<0, start被重置为length+start
test_string.substr(-1,2) // "d"
等同于:
test_string.substr(10,2) // "d"
从length-4开始截取绝对值个数字符串
test_string.substr(-4) // "orld"
等同于:
test_string.substr(length-4,|-4|) // "orld"