新增字符串方法 : slice(),substring(),substr()

本文详细比较了JavaScript中三种常用的字符串截取方法:substring(), slice() 和 substr()。通过具体的代码示例,展示了不同参数设置下这些方法的行为差异,帮助开发者更好地理解和选择合适的字符串操作方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

var str = 'hello-world!';  //字符串长度 11

//   传入一个参数
   console.log(str.substring(2));    //llo-world!
   console.log(str.slice(2));    //llo-world!
   console.log(str.substr(2));    //llo-world!
   console.log('-------');

//   传入两个参数 两个参数都为正数
    console.log(str.substring(2,6));     //llo
    console.log(str.slice(2,6));         //llo
    console.log(str.substr(2,6));        //llo-wo
   console.log('-------');

//    传入两个参数,一个参数为负数
   console.log(str.substring(-5,8));  //hello-wo
   console.log(str.slice(-5,8));      //o
   console.log(str.substr(-5,8));    //orld!
   console.log('-------');

   console.log(str.substring(5,-8));  //hello
   console.log(str.slice(5,-8));     //''
   console.log(str.substr(5,-8));    //''
   console.log('-------');

   console.log(str.substring(0,3));    //hel
   console.log(str.substring(3,-3));    //hel
   console.log(str.substring(-3,3));    //hel
   console.log(str.substring(3,0));    //hel

   console.log('---');

   console.log(str.slice(-8));  //o-world!
   console.log(str.slice(-20,10));   //hello-worl
   console.log(str.substr(-8));  //o-world!
   console.log(str.substr(-20,10));   //hello-worl


   //1.substring(),slice()  参数都为正数意义一样,都是从哪到哪,substr()则是从哪到后面多少位;
   //2.substring()任何参数为负数都转为零,如果有一参数不是负数,则都变为从零到哪(如substring(-3,3)   //  substring(0,3)substring(3,-3)substring(3,0)都是一样的结果)
   //3.substr(),slice()  传入的第一个参数是负数,如果负数的绝对值小于字符串的长度,则转换成字符串长度+负数
   // (如:11+-8=3)的正数,否则为零;
   //4.substr(),slice()  传入的第二个参数是负数,slice()将其转为正数或零,substr()则直接转为零;
    
    
    
    
    


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值