substr与substring
substring
substring() 方法返回一个字符串在开始索引到结束索引之间的一个子集,或者从开始索引到字符串末尾的一个子集
str.substring(indexStart[,indexEnd])
indexStart:需要截取的第一个字符的索引,该索引位置的字符作为返回的字符串的收字母
indexEnd:可选,一个0到字符串长度之间的整数,以该数字为索引的字符不包含在截取的字符串中。
let str='0123456789'
//一个参数
console.log(str.substring(0)) //0123456789
console.log(str.substring(2)) //23456789
console.log(str.substring(7)) //789
console.log(str.substring(10)) //
//两个参数
console.log(str.substring(0,10)) //0123456789
console.log(str.substring(2,6)) //2345
console.log(str.substring(7,9)) //78
console.log(str.substring(3,4)) //3
substr()
substr()
方法返回一个字符串中从指定位置开始到指定字符数的字符。
str.substr(start[, length])
start:开始提取字符的位置。如果为负值,则被看作 strLength + start
,其中 strLength
为字符串的长度(例如,如果 start
为 -3
,则被看作 strLength + (-3)
length:可选。提取的字符数。
let str='0123456789'
//一个参数
console.log(str.substr(0)) //0123456789
console.log(str.substr(10)) //
console.log(str.substr(-5)) //56789
//两个参数
console.log(str.substr(0,1)) //0
console.log(str.substr(0,10)) //0123456789
console.log(str.substr(-5,10)) //56789