你不知道的slice,substr,substring异同,slicesubstring
你不知道的slice,substr,substring异同,slicesubstring
slice(),substr(),substring()
是基于基于子字符串创建新字符串的方法,
相同点:
都会返回被操作字符串的一个子字符串
都会接收1·-2个参数
如果没有指定第二个参数,则字符串的末尾作为结束位置
都不会改变原始字符串
不同点:
slice(),substring()
的第一个参数指定子字符串的开始位置,若指定第二个参数,则第二个参数表示结束位置
-substr()
第一个参数同样指定的是开始位置,若指定第二个参数,第二个参数指定的是返回的字符个数
更多隐形扩展下面~~~
下面根据参数的数量,正负
进行归纳,便于记忆:
1.当这三种方法只接受1个参数
的情况下:
(1)
若此参数为正:
var a = 'www.shaotianyu.com';
console.log(a.slice(3)); //.shaotianyu.com
console.log(a.substr(3)); //.shaotianyu.com
console.log(a.substring(3)); //.shaotianyu.com
(2)
若此参数为负:
var a = 'www.shaotianyu.com';
console.log(a.slice(-3)) //com
console.log(a.substr(-3)) //com
console.log(a.substring(-3)) //www.shaotianyu.com
分析:
a.slice(-3)
和a.substr(-3)
返回的结果相同,因为-3
会被转化为a.length+(-3)
,也就是等同调用了a.slice(15)
和a.substr(15)
,所以结果返回com
。
但是substring()
方法不同,当它接收参数为负,将会将参数转化为0
,也就是说,a.substring(-3) => a.substring(0)
,所以返回的是整个原始字符串。
2.当这三种方法接受2个参数
的情况下:
(1)
若参数1为正,参数2为正:
var a = 'www.shaotianyu.com';
console.log(a.slice(4,13)) //shaotiany
console.log(a.substr(4,13)) //shaotianyu.co
console.log(a.substring(4,13)) //shaotiany
分析:
a.slice(4,13),a.substring(4,13)
返回的是从位置4
开始,位置13
结束(不包括13
)的子字符串;
a.substr(4,13)
返回的是从位置4
开始,返回字符个数为13
的子字符串,所以返回shaotianyu.co
(2)
若参数1为正,参数2为负:
此种情况下,三种方法的行为各不相同。
var a = 'www.shaotianyu.com';
console.log(a.slice(4,-3)) //shaotianyu.
console.log(a.substr(4,-3)) //""
console.log(a.substring(4,-3)) //www.
分析:
上面的demo中,a.slice(4,-3)
相当于调用a.slice(4,15)
,所以返回shaotianyu.
a.substr(4,-3)
在接收的第二个参数为负时,也会将第二个参数转化为0
,也就是相当于调用a.substr(4,0)
,意味着返回包含0
个字符串的子字符串,也就是空字符串
a.substring(4,-3)
会把第二个参数为负时转化为0
,转化为a.substring(4,0)
,不过,这个方法会将较小的数作为开始位置,较大的数转化为结束位置,所以最终相当于调用a.substring(0,4)
,所以结果返回www.
相关文章
- 暂无相关文章
用户点评