JS 三种截取字符串方法

三种方法分别是:

  • slice( )
  • substring( )
  • substr( )

slice(start, end) 和 substring(start, end)

参数:start:开始截取的索引(包含) end:结束截取的索引(不包含)

定义:该两种方法可提取字符串的某个部分,并返回被提取的部分

提示:如果参数为负数,则从字符串的尾部开始算起,-1指的是最后一个字符,-2指的是倒数第二个字符,以此类推。

 

substr(start, length)

参数:start:开始截取的索引(包含) length:截取字符的个数

 

string.slice(start, end)

        var str = 'hello world';
        console.log(str.length);        // 11
        console.log(str.slice(0));      // 'hello world' 从索引为0的字符开始,截取到最后一个字符
        console.log(str.slice(2, 9));   // 'llo wor' 从索引为为2的字符开始,截取到索引为8(9-1)的字符

        // 当参数为负数时,让它和字符串的length的值相加,-3+11=8,此时相当于str.slice(8)
        console.log(str.slice(-3));     // 'rld' 从索引为8的字符开始,截取到最后一个字符
        console.log(str.slice(-8, -2)); // 'lo wor' -8+11=3; -2+11=9,相当于从索引为3的字符开始,截取到索引为8(9-1)的字符
        console.log(str.slice(3, 9));   // 'lo wor'

 

string.substring(start, end)

        var str = 'hello world';
        console.log(str.length);            // 11
        console.log(str.substring(0));      // 'hello world' 从索引为0的字符开始,截取到最后一个字符
        console.log(str.substring(2, 9));   // 'llo wor' 从索引为为2的字符开始,截取到索引为8(9-1)的字符

        // 当参数为负数时,substring() 的处理是把负数变为 0;并且总是把较小的数作为起始位置
        console.log(str.substring(-3));     // 'hello world' -3 => 0 从索引为0的字符开始,截取到最后一个字符
        console.log(str.substring(3, -2));  // 'hel' (3, -2)=> (0, 3)相当于从索引为0的字符开始,截取到索引为3的字符
        console.log(str.substring(0, 3));   // 'hel'

 

string.substr(start, length)

        var str = 'hello world';
        console.log(str.length);         // 11
        console.log(str.substr(0));      // 'hello world' 从索引为0的字符开始,截取到最后一个字符
        console.log(str.substr(2, 8));   // 'llo worl' 从索引为为2的字符开始,截取8个字符(空格也算一个字符)

        // 当参数为负数时,让它和字符串的length的值相加
        console.log(str.substr(-3));     // 'rld' -3+11=8 从索引为8的字符开始,截取到最后一个字符
        console.log(str.substr(-3, 2));  // 'rl' (-3, 2)=> (8, 2)相当于从索引为8的字符开始,截取2个字符

 

区别

三个方法的区别在于对 负数 的处理方式不同

slice( ):当参数为负数时,让它和字符串的length的值相加,转成正数。substr 也一样

substring( ):当参数为负数时,substring() 的处理是把负数变为 0;并且总是把较小的数作为起始位置

 

--- cezlz ---

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值