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) + "|" + "
");
打印效果
1 |12345|2 |123456|3 |6|4 IE: |12| Chrome: |23|5 ||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) + "|" + "
");
打印效果
1 |12345|2 |123456|3 |2345|4 |12|5 ||6 |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) + "|" + "
");
打印效果
1 |12345|2 |123456|3 ||4 |2|5 ||6 ||如果你预想的结果和打印效果完全一致,那你的基本功一定不赖。如果多少有点犹豫或者结果出乎你的意料,那我的文章多少也有点用处了。
总结
substr
该方法的arg2和其它两个方法的arg2压根就代表不同意义,所以单独揪出来。
当arg1<0时,不同浏览器的结果不同。IE 直接将arg1改成0, Chrome 下标读取方式由原来的从左往右读改成从右往左读
substring和slice
(1)arg2 > arg1,即参数2大于参数1时
substring:自动颠倒位置,数值大的在arg2位置上,数值小的在arg1位置上
slice:返回空字符串
(2)对负数的处理
substring:将数值为负数的参数转换为0
slice:将数值为负数的参数转换为(字符串长度-参数数值)
创造与魔法九游版本
创造与魔法九游版采用了极致创新的魔幻游戏玩法感受,游戏具备最
疯狂医院达什医生中文版(Crazy Hospital)
疯狂医院达什医生最新版是一款医院模拟经营类游戏,逼真的场景画
宝宝庄园官方版
宝宝庄园官方版是一款超级经典好玩的模拟经营类型的手游,这个游
桃源记官方正版
桃源记是一款休闲娱乐类的水墨手绘风格打造的模拟经营手游。玩家
长途巴士模拟器手机版
长途巴士模拟器汉化版是一款十分比真好玩的大巴车模拟驾驶运营类