substring(),substr(),slice()的区别
1、substring
substring() 方法用于提取字符串中介于两个指定下标之间的字符。
- 若substring(x) ,当其中只有一个下标时,会输入从x开始到结尾的string
- 若substring(x,y) ,当其中有两个下标时,会输入从最小值到最大值之间的string(若y为负数,则输入x之前的string)
举例:
var str = 'hello world'
console.log(str.substring(1)) //输出结果为ello world
console.log(str.substring(1,3)) //输出结果为el
console.log(str.substring(3,1)) //输出结果为el
console.log(str.substring(1,-3)) //输出结果为h
2、substr
substr() 方法可在字符串中抽取从 start 下标开始的指定数目的字符。
- 若substr(x) ,当其中只有一个下标时,会输入从x开始到结尾的string
- 若substr(x,y) ,当其中有两个下标时,x元素表示字符起始位置,y表示字符长度 (若y为负数,则输出为空)
举例:
var str = 'hello world'
console.log(str.substr(1)) //输出结果为ello world
console.log(str.substr(1,3)) //输出结果为ell
console.log(str.substr(3,1)) //输出结果为l
2、slice
slice() 方法可在字符串中抽取从 start 下标开始的指定数目的字符。
- 若slice(x) ,当其中只有一个下标时,会输入从x开始到结尾的string
- 若slice(x,y) ,当其中有两个下标时,会输入从x到y之间的string (若y为负数,输出的的是y+length之后的长度)
举例:
var str = 'hello world' console.log(str.slice(1)) //输出结果为ello world console.log(str.slice(1,3)) //输出结果为el console.log(str.slice(3,1)) //输出结果为空 console.log(str.slice(1,-3)) //输出结果为ello wo

浙公网安备 33010602011771号