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


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值