欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > > 文章正文

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

来源: javaer 分享于  点击 27157 次 点评:126

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


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()则直接转为零;
    
    
    
    
    


相关文章

    暂无相关文章

用户点评