【Javascript】IE下substr()函数截取末尾字符时的问题
- If start is negative, Internet Explorer returns the whole string. That’s wrong! IE should use the last character in the string.
- If start equals stop
,
it returns an empty string. - If stop is omitted, it extracts characters to the end of the string.
- If either argument is less than 0 or is NaN, it is treated as if it were 0.
- If either argument is greater than string’s length, either argument will use string’s length.
- If start > stop, then substring will swap those 2 arguments
- If stop is omitted, slice extracted chars to the end of the string, exactly like substring().
- If start > stop, slice() will NOT swap the 2 arguments.
- If start is negative, slice() will set char from the end of string, exactly like substr() in Firefox. This behavior is observed in both Firefox and IE.
- If stop is negative, slice() will set stop to: (string.length – 1) – stop (original value).
这两天刚遇到一个问题,substr()函数在IE和FF下表现不一致,导致了一个IE下的bug。
可以通过以下代码来测试:
提示:你可以先修改部分代码再运行。
希望得到的是c,FF下表现正常;但跑到IE下,显示abc,不是期望的结果。看来IE在处理substr()第一个参数为负数的情况处理方式不一样。
为了解决问题,另觅蹊径,改用substring()函数代替substr()
提示:你可以先修改部分代码再运行。
p.s. 附一篇学习文章:substr() vs substring() vs slice()
substr()
substr() method extracts a specified number of characters in a string, from a start index.
Syntax: string.substr(start, length);
Quick Notes aout Substr:
substring()
substring() method extracts the chars in a string between two specified indexes.
Syntax: string.substring(start, stop);
Quick Notes about Substring:
slice()
slice() works like substring() with a few different behaviors.
Syntax: string.slice(start, stop);
Quick Notes about Slice:
参考:Javascript: substr() v.s. substring()
标签: Javascript
还没有人抢沙发呢~