【转】slice,substr和substring的区别

substr(start [, length])
substring(start [, end])
slice(start [, end])

① 从定义上看: substring和slice是同类的,参数都是字符串的某个{开始}位置到某个{结束}位置(但{结束}位置的字符不包括在结果中);而substr则是字符串的某个{开始}位置起,数length个长度的字符才结束。-- 共性:从start开始,如果没有第2个参数,都是直到字符串末尾。

② substring和slice的区别则是,slice可以接受“负数”,表示从字符串尾部开始计数; 而substring则把负数或其它无效的数,当作0。

1
2
"hello world!" .slice(-6, -1)  // "world"
"hello world!" .substring( "abc" , 5)  // "hello"

③ substr的start也可接受负数,也表示从字符串尾部计数,这点和slice相同;但substr的length则不能小于1,否则返回空字符串

1
2
"hello world!" .substr(-6, 5)  // "world"
"hello world!" .substr(0, -1)  // ""

所以: 很多人认为substring是多余的:如果只知道位置,那么用slice;如果知道长度,则用substr。

猜你喜欢

转载自mmww1024.iteye.com/blog/2338523