zoukankan      html  css  js  c++  java
  • slice,substring,substr的区别

    1.都为正整数
    //
    例子数据 var arr = [1,2,3,4,5,6,7], var str = "helloworld!"; //注意这里有个!号也算一位若有空格,空格也算一位 console.log(str.slice(1)); //elloworld! console.log(str.substring(1)); //elloworld! console.log(str.substr(1)); //elloworld! console.log(arr.slice(1)); //[2,3,4,5,6,7] console.log(arr.substr(1)); //TypeError: arr.substr is not a function console.log(arr.substring(1)); //TypeError: arr.substring is not a function 数组是没有substr和substring方法的,含str的都是字符串专用

    2.都是正整数第一个小于第二个

    //例子不变
    console.log(str.slice(1,4));  //ell 不包含结束位1起始位,4结束位
    console.log(str.substring(1,4));  //ell 不包含结束位1起始位,4结束位
    console.log(str.substr(1,4)); //ello  不一致了!!! 
     
    console.log(arr.slice(1,4)); //[2,3,4]  不包含结束位1起始位,4结束位
    

      

    3. 都使用两个正数参数(第一个大于第二个):
    var arr = [1,2,3,4,5,6,7],
    var  str = "helloworld!";
    console.log(str.slice(5,1));  //""
    console.log(str.substring(5,1));  //ello
    console.log(str.substr(5,1));  //"w"
     
    console.log(arr.slice(5,1));  //[]
    

      substring会将此情况的位置自动调换,然后截取出相应的值;substr当然按照原意从第5个位置开始,截取1位返回一个字符;而slice直接返回空,slice的第一参数必须要小于等于第二参数才有效

    4。前正后负

    var arr = [1,2,3,4,5,6,7],
    var str = "helloworld!";
    console.log(str.slice(1,-2)); //elloworl
    console.log(str.substr(1,-2));  //""
    console.log(str.substring(1,-2));  //h
     
    console.log(arr.slice(1,-2)); //[ 2, 3, 4, 5]
    

    slice第二参数为负数时,是从尾部倒数来计算或者说是与字符串或数组的长度相加得出的结果来计算;而substring, 无论第二参数是负多少,都只截取了第一个字符;substr同样,个数不可能是负数,所以是空;总结substring和substr第二参数为负数时其实是无效果的。

    5.前负后正

    //例子不变
    console.log(str.slice(-3,1))  //""
    console.log(str.substr(-3,1))  //l
    console.log(str.substring(-3,1))  //h
     
    console.log(arr.slice(-3,1))  //[]

    slice结果是空,这个结合第3和第4种情况,可知,这个实际是slice(4,1),第一参数大于第二参数了,所以是无效的,空值;substring,结合第3和第4种情况,是调换了顺序,但是还是负数,依然也是无效的,只返回第一个字符;substr,第一参数负数同样代表从尾部倒数或者字符串的长度相加得出的结果来计算,等同于substr(8,1),截取栗子中的一位,得到了“l”。
    6.全为负数

    //例子不变
    console.log(str.slice(-1,-5));
    console.log(str.substr(-1,-5));
    console.log(str.substring(-1,-5));
     
    console.log(arr.slice(-1,-5));
    //上面的结果全是空
            
    console.log(str.slice(-5,-1)); //orld
    console.log(str.substr(-5,-1)); //""
    console.log(str.substring(-5,-1)); //""
     
    console.log(arr.slice(-5,-1)); //[ 3, 4, 5, 6 ]

    总结:

    1.slice,substring,substr 都是用来截取字符串的,然而数组只能使用slice,这三者如果不传参数,则都返回全部内容;

    2.  参数为正数时,只有substring会自动调换顺序,slice在第一参数大于第二参数时会无效返回空,而substr无所谓,除非给定的第一参数超出了源数据长度才会返回空;

    3. 参数为负数时,只有substring会永远无效,即不要给substring使用负值!slice可认为从尾部倒数,或者直接用源数据长度加上这个负值换算为正数,然后结论依然遵循第2条所述;而substr,则只适用第一参数为负数,换算方法同slice,其第二参数代表截取的个数,是不能为负数的;


    以上内容通过个人学习,博客项目学习,w3c总结,望各位大神多多指点,谢谢!

  • 相关阅读:
    js基础之弹性运动(四)
    js基础之动画(三)
    js基础之动画(二)
    js基础之动画(一)
    js基础之ajax
    js基础之COOKIE
    4.27日软件开发日记我今天做了什么
    4.25日
    4.24日自学成果
    错排公式及其化简
  • 原文地址:https://www.cnblogs.com/fms-3/p/10237714.html
Copyright © 2011-2022 走看看