substring,substr,和slice的区别详解。

1.Substring(x,y) : 输出一个字符串,当其中只有一个参数时,会输出从x开始到结尾的String。

举例:

var str="hello";
       console.log(str.substring(1));

输出结果为ello

如果有两个参数,则会输出从x到y的值,值得注意的时候,这里的x ,y可以理解成一个

(x, y]的区间,即不包含第x个元素,但包含第y个元素, x,y均从1开始计算

举例:


var str="helloworld";
       console.log(str.substring(2,5));

输出结果为llo。

另外当x<y的情况时,系统会自动调整x,y的位置并输出也就是说

var str="helloworld";
       console.log(str.substring(5,2));

这俩个结果是一样的。

如y为负值,则直接输出为x之前的字符串

举例

var str="helloworld";
       console.log(str.substring(3,-5));

结果为hel;

2.Substr(x,y): 和substring不同,substr内的x,y属性分别代表元素的起始位置,及输出的元素长度。举例:

var str="helloworld";
       console.log(str.substr(2,5));

输出结果为:llowo

因为x,y两个参数的属性不同,所以相互调换位置时,并没有歧义,而是正常输出。但当y为负值时,则为空。

举例:

var str="helloworld";
       console.log(str.substr(3,-5));

结果为空

3.slice(x,y) 和substring类似,都是返回一个(x, y]区间的字符串,唯一不同需要注意的情况是,如果x>y的情况发生,则会产生一个空,而不会自动调换位置。举例:

var str="helloworld";
       console.log(str.slice(2,5));

输出结果为llo

var str="helloworld";
       console.log(str.slice(5,2));

结果为空

特别注意,在这里y可以为负值。输出的的是y+length之后的长度,举例:

var str="helloworld";
       console.log(str.slice(3,-2));

输出结果为 其length值为10,则真实输出应为

3,(10-2); 结果为lowor

原文地址:https://www.cnblogs.com/yuyufeng/p/5532426.html