substr、substring和slice小记

前不久逛园子看到一篇文章,ASP.net—Textbox的技巧使用,文章中有一处写到onkeyup="this.value = this.value.slice(0, 1000)",我是菜鸟,还真没有用过slice,所以查些资料补习了一下。
关于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小记substr、substring和slice小记打印效果 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:将数值为负数的参数转换为(字符串长度-参数数值)
Tags: 

延伸阅读

最新评论

发表评论