一,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 worlconsole.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