• [javascript string] slice();substr();substring();之间的区别


    今天遇到这个问题,发现ぜんぜんわすねまます
    3个方法,直接上代码吧,[网络版本较多就不注明参考过哪些了 -0- ]

     1     var test = 'hello world';
     2 
     3     //均一位参数测试
     4     console.log(test.slice(2));         //llo world
     5     console.log(test);  //hello world
     6     console.log(test.substr(2));        //llo world
     7     console.log(test);  //hello world
     8     console.log(test.substring(2));     //llo world
     9     console.log(test);  //hello world
    10     //---1个整数传参返回结果一样,亦不会影响原来的字符串
    11     console.log(test.slice(-2));         //ld
    12     console.log(test);  //hello world
    13     console.log(test.substr(-2));        //ld
    14     console.log(test);  //hello world
    15     console.log(test.substring(-2));     //hello world
    16     console.log(test);  //hello world
    17 //    //---1个负数传参不会影响原来的字符串
    18 //    //str.slice(a); str.substr(a);返回结果为字符串从右往左两位
    19 //    //而 str.substring();则返回字符串本身
    20 
    21     //均两位参数测试
    22     console.log(test.slice(4,7));       //o w
    23     console.log(test);  //hello world
    24     console.log(test.substr(4,7));      //o world
    25     console.log(test);  //hello world
    26     console.log(test.substring(4,7));   //o w
    27 //    console.log(test);  //hello world
    28     //第2位传参为正整数
    29     //1.都不会改变原有str的长度
    30     //2.str.slice(a,b); str.substring(a,b);
    31         //均为下标0起,由下标a到下标b截取的值
    32     //       str.substr(a,b); //与前两个方法有区别
    33         //获得结果为截取下标0起,由下标a起往后b位下标
    34 
    35     console.log(test.slice(4,-3));       //o wo
    36     console.log(test);  //hello world
    37     console.log(test.substr(4,-3));      // (空)
    38     console.log(test);  //hello world
    39     console.log(test.substring(4,-3));   //hell
    40     console.log(test);  //hello world
    41     //第2位传参为负整数
    42     //1.都不会改变原有str的长度
    43     //2.test.slice(a,b);        获得为下标0起,由下标a起往后b位下标截取(下标0起,即-3为下标4)
    44     //  test.substr(a,b);       返回为空
    45     //  test.substring(a,b);    获得为下标0起,由下标a起往前b位下标截取(下标0起,即-3为下标4)
  • 相关阅读:
    [MongoDB] Remove, update, create document
    [AngularJS + RxJS] Search with RxJS
    [Redux] Passing the Store Down with <Provider> from React Redux
    [Redux] Passing the Store Down Implicitly via Context
    [Redux] Passing the Store Down Explicitly via Props
    [Cycle.js] Generalizing run() function for more types of sources
    [Redux] Extracting Container Components -- Complete
    [Redux] Redux: Extracting Container Components -- AddTodo
    视觉暂留:视觉暂留
    人物-发明家-贝尔:亚历山大·贝尔
  • 原文地址:https://www.cnblogs.com/me2o/p/7887722.html
Copyright © 2020-2023  润新知