js中string的三种创建新字符串(截取)方法

在字符串中创建新字符串的方法我们今天介绍三种,slicesubstringsubstr

我们先介绍一下它们三个的区别
str.slice(start, end), start<= 字符 < end , 如果是负数就是从后向前找;
str.substring(start, end),当参数为正数时start<= 字符 < end ,当参数为负数时,对应索引为0(无论是第一个参数还是第二个参数)小的数为start, 大的数为end;
str.substr(index,howmany),第一个数为其实位置的下标,第二个数为要截取几个;

下面我们用实际的例子来看看

var str = "hello world";
console.log(str.slice(6));   //"world"
console.log(str.substring(6));  //"world"
console.log(str.substr(6));      //"world"

当有一个参数的时候是不是三个都一样

var str = "hello world";
console.log(str.slice(2,7));    //"llo w"
console.log(str.substring(2,7)); //"llo w"
console.log(str.substr(2,7));  //"llo worl"

同样是(2,7)substr是不是就不一样了呢,因为它的7是往后截取7个;

var str = "hello world";
    console.log(str.slice(-3));    //"rld"  
    console.log(str.substring(-3);  //"hello world"  此方法的参数是负数都转换为0
    console.log(str.substr(-3));    //"rld"
    console.log(str.slice(3,-4));   //"lo w"
    console.log(str.substring(3,-4)); //"hel"  负数对应索引为0;小的数为start, 大的数为end;所以它其实就变成了str.substring(0,3);
    console.log(str.substr(3,-4));   //""(空字符串)

看完例子是不是清晰了很多!!!

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容