美文网首页
JavaScript字符串操作方法 slice、substr、s

JavaScript字符串操作方法 slice、substr、s

作者: bpup | 来源:发表于2017-06-16 16:07 被阅读0次

    slice(start,end)

    定义:接受一个或者两个参数,第一个参数指定子字符串的开始位置。第二个参数表示子字符串的结束位置(不包括结束位置的那个字符),如果没有传递第二个参数,则将字符串的最后一位作为结束位置。

    ** slice(start)**

              var str="helloString";
              console.log(str.slice(5)) //单个参数,返回5到最后之间的字符    String
              console.log(str.slice(3)) //单个参数,返回3到最后之间的字符    loString
    

    **slice(start,end) **

              var str="helloString";
              console.log(str.slice(5,8)) //两个参数,返回5到最后之间8的字符    Str 
              console.log(str.slice(3,6)) //两个参数,返回3到最后之间6的字符    loS
    

    当参数为负数情况
    slice()方法会将传入的负值与字符串长度相加。

              var str="helloString";
              console.log(str.length); //11
              console.log(str.slice(-5)) //  11-5=6 从第6个到最后    tring
              console.log(str.slice(-6,-2)) //两个参数,11-6=5;11-2=9 5-9之间  Stri
    

    第二个参数比第一个参数值小的情况

              var str="helloString";
              console.log(str.slice(9,5)) // 返回空字符串
              console.log(str.slice(-2,-6)) // 返回空字符串
    

    ** 不传参数的情况直接返回整个字符串**

               var str="helloString";
               console.log(str.slice()) // helloString
    

    substring(start,end)

    定义:接受一个或者两个参数,第一个参数指定子字符串的开始位置。第二个参数表示子字符串的结束位置(不包括结束位置的那个字符),如果没有传递第二个参数,则将字符串的长度作为结束位置。

    大部分情况与slice()相同,主要有以下几点不也一样

    • 当第二个参数比第一个小的时候,substring会自动转化参数位置,如下

              var str="helloString";
              console.log(str.substring(7,5)) //St
              console.log(str.substring(5,7)) //St
      
    • 当有参数为负数时,负数会自动转为0,如下
      var str="helloString";
      console.log(str.substring(-6)) //helloString -6转为0
      console.log(str.substring(-1,-2)) //空字符串
      console.log(str.substring(3,-1)) // 0-3之间 hel


    substr(start,length)

    定义:接受一个或者两个参数,第一个参数指定子字符串的开始位置。第二个参数跟之前的方法有些区别,表示返回的字符个数。如果没有传递第二个参数,则将字符串的长度作为结束位置。来看例子:

              var str="helloString"; 
              console.log(str.substr())   //helloString
              console.log(str.substr(3))   //3-最后 loString
              console.log(str.substr(3,5))   //从3开始往后数5个字符 loStr
              console.log(str.substr(10,1))   //从10开始往后数1个字符 g
              console.log(str.substr(10,2))   //从10开始往后数2个字符 g,超过字符串长度按最低有效值计算
    

    有负数情况

              var str="helloString"; 
              console.log(str.substr())   //helloString
              console.log(str.substr(-3))   //11-3=8,8-最后 ing
              console.log(str.substr(-3,-6))   //空
              console.log(str.substr(5,-1))   //空 只要长度为负数返回为空
    

    相关文章

      网友评论

          本文标题:JavaScript字符串操作方法 slice、substr、s

          本文链接:https://www.haomeiwen.com/subject/jucmqxtx.html