欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > > 文章正文

JS中substr(),substring(),slice()区别,substrslice

来源: javaer 分享于  点击 9765 次 点评:275

JS中substr(),substring(),slice()区别,substrslice


一,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;

三,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(a.substring(4,-2)); //2345 

substring() 会把较小的值作为开始位置,较大的值为结束位置

相关文章

    暂无相关文章

用户点评