关于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) + "|" + "
");
![substr、substring和slice小记](/Files/20119/40404a4e-63ae-49f0-bf45-94afd961a5ad.gif)
![substr、substring和slice小记](/Files/20119/b2fc231d-b5e9-4b48-9e3e-080b79a353e6.gif)
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) + "|" + "
");
![](/Files/20119/40404a4e-63ae-49f0-bf45-94afd961a5ad.gif)
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) + "|" + "
");
![](/Files/20119/40404a4e-63ae-49f0-bf45-94afd961a5ad.gif)
如果你预想的结果和打印效果完全一致,那你的基本功一定不赖。如果多少有点犹豫或者结果出乎你的意料,那我的文章多少也有点用处了。
总结
substr
该方法的arg2和其它两个方法的arg2压根就代表不同意义,所以单独揪出来。
当arg1<0时,不同浏览器的结果不同。IE 直接将arg1改成0, Chrome 下标读取方式由原来的从左往右读改成从右往左读
substring和slice
(1)arg2 > arg1,即参数2大于参数1时
substring:自动颠倒位置,数值大的在arg2位置上,数值小的在arg1位置上 slice:返回空字符串
(2)对负数的处理
substring:将数值为负数的参数转换为0 slice:将数值为负数的参数转换为(字符串长度-参数数值)
最新评论