关于substr、substring和slice方法区别的文章,网上搜到了许多,文章内容也基本一致。而后,我将其中一篇文章中的代码挪到本地进行了测试,发现测试结果和原文中的有些出入。

我更相信自己亲自验证过后的代码,随后小记下来,供以后查阅。

substr
代码如下:

document.write("|" + str.substr(0,5) + "|" + "
");
document.write("|" + str.substr(0) + "|" + "
");
document.write("|" + str.substr(5,1) + "|" + "
");
document.write("|" + str.substr(-5,2) + "|" + "
");
document.write("|" + str.substr(-2,-5) + "|" + "
");

打印效果

|12345|
|123456|
|6|
IE: |12| Chrome: |23|


substring
代码如下:

document.write("|" + str.substring(0,5) + "|" + "
");
document.write("|" + str.substring(0) + "|" + "
");
document.write("|" + str.substring(5,1) + "|" + "
");
document.write("|" + str.substring(-5,2) + "|" + "
");
document.write("|" + str.substring(-2,-5) + "|" + "
");
document.write("|" + str.substring(2,-5) + "|" + "
");

打印效果
|12345|
|123456|
|2345|
|12|

|12|
slice
代码如下:

document.write("|" + str.slice(0,5) + "|" + "
");
document.write("|" + str.slice(0) + "|" + "
");
document.write("|" + str.slice(5,1) + "|" + "
");
document.write("|" + str.slice(-5,2) + "|" + "
");
document.write("|" + str.slice(-2,-5) + "|" + "
");
document.write("|" + str.slice(2,-5) + "|" + "
");

打印效果
|12345|
|123456|

|2|

||
如果你预想的结果和打印效果完全一致,那你的基本功一定不赖。如果多少有点犹豫或者结果出乎你的意料,那我的文章多少也有点用处了。

总结

substr

该方法的arg2和其它两个方法的arg2压根就代表不同意义,所以单独揪出来。

当arg1
substring和slice

(1)arg2 > arg1,即参数2大于参数1时

substring:自动颠倒位置,数值大的在arg2位置上,数值小的在arg1位置上
slice:返回空字符串

(2)对负数的处理

substring:将数值为负数的参数转换为0
slice:将数值为负数的参数转换为(字符串长度-参数数值)
09-16 16:35