zoukankan      html  css  js  c++  java
  • JavaScript中substr(),substring(),slice()区别

    一,substr()

    var testStr = “Hello world!”;
    console.log(testStr.substr(3,4)); //lo w;
    console.log(testStr.substr(3)); //lo world!;
    console.log(testStr.substr(3,10)); //lo world!;
    console.log(testStr.substr(-1)); //!;
    console.log(testStr.substr(-1,3)); //!;

    二,substring()

    var testStr = “Hello world!”;
    console.log(testStr.substring(3,4)); //l;
    console.log(testStr.substring(4,1)); //ell;
    console.log(testStr.substring(3)); //lo world!;
    console.log(testStr.substring(3,10)); //lo worl;
    console.log(testStr.substring(-1)); //Hello world!
    console.log(testStr.substring(-1,3)); //Hel;

    注意

    console.log(testStr.substring(3,-1)); //Hel;

    三,slice()

    var testStr = “Hello world!”;
    console.log(testStr.slice(3,4)); //l;
    console.log(testStr.slice(4,1)); //空字符;
    console.log(testStr.slice(3)); //lo world!;
    console.log(testStr.slice(3,10)); //lo worl
    console.log(testStr.slice(-1)); //!;
    console.log(testStr.slice(-3)); //ld!;
    console.log(testStr.slice(-1,3)); //空字符;

    总结
    slice(index,index) substr(index,length),subtring(index,index)
    只指定一个参数(正整数)时,返回的结果都一样

    传递负值参数时,slice() 会将传入的负值和字符串的长度相加;

            substr() 会将参数的第一个参数加上字符串的长度,将第二个负值参数转换成0;

            substring() 会将所有的负值转换成0

    后面这个应该很少人注意

    var num = "2345678";
    alert( num.substring(4,-2));  //2345

    substring() 会把较小的值作为开始位置,较大的值为结束位置
    ————————————————
    版权声明:本文为CSDN博主「WebFrontEnd_TL」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
    原文链接:https://blog.csdn.net/u013270347/article/details/80751874

  • 相关阅读:
    设备树(Device Tree)
    深度Linux Deepin系统安装教程使用体验
    Qt Creator的安装与Qt交叉编译的配置
    移植tslib和Qt5.6到三星s5pv210开发板
    Linux下读取RFID卡号(C串口编程)
    如何移植openwrt系统
    如何在Qt Creator中添加库文件和头文件目录
    Qt Creator中如何选择某个子项目为启动项目
    QT中子目录调用另一个子目录
    在Qt项目中如何添加一个已有的项目作为子项目
  • 原文地址:https://www.cnblogs.com/yungiu/p/11491195.html
Copyright © 2011-2022 走看看