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

  • 相关阅读:
    ViewGroup和View
    十二、Android UI开发专题(转)
    十一、Android学习笔记_AsyncQueryHandler的应用
    十、Notepad++正则表达式使用
    九、Android学习笔记_ Android开发中使用软引用和弱引用防止内存溢出
    八、android jni 之C语言基础
    七、Android学习笔记_JNI hello world
    六、Android学习笔记_JNI_c调用java代码
    五、PackageManager获取版本号
    四、 Android之手机屏幕朝向
  • 原文地址:https://www.cnblogs.com/yungiu/p/11491195.html
Copyright © 2011-2022 走看看