It is very common to extract part of a string in computer programming and there is no exception in Javascript. Here are 2 functions for string extraction
- aString.substr(start, length)
- aString.substring(start, stop)
In this post, i would focus on the substr() function. The following example demonstrate how substr() works in Firefox, Chrome and Safari.
<html> <head> <title>substr() problem in Internet Explorer</title> <script type="text/javascript"> var testString = "0123456789"; function showResult() { alert(testString.substr(2)); // Output: 23456789 alert(testString.substr(2, 5)); // Output: 23456 alert(testString.substr(-3)); // Output: 789 alert(testString.substr(-5, 2)); // Output: 56 } </script> </head> <body onload="javascript:showResult();"> </body> </html>
It seems that everything is straight forward, but try the above HTML in the greatest browser which is called Internet Explorer, you will get
... alert(testString.substr(-3)); // IE Output: 0123456789 alert(testString.substr(-5, 2)); // IE Output: 01 ...
Whenever the start index is negative, Internet Explorer treat it as 0. A simple workaround is replace the substr() function with slice(). the slice() function behaves just like the substring() function which is
- aString.slice(start, stop)
... //alert(testString.substr(-3)); alert(testString.slice(-3)); // Output: 789 //alert(testString.substr(-5, 2)); alert(testString.slice(-5, (testString.length-5)+2)); // Output: 56 ...
Done =)
Reference: Javascript: substr() v.s. substring()
Thanks so much for posting this. I guess I’ve never tried to do this before so it caught me by surprise that it didn’t work in IE when it functions the same in every other implementation of substr().
LikeLike
IE has many unexpected behaviors~ i wish it will be extinct soon… =P
LikeLike
I know this is an old post, but we still have some users who have XP machines with IE7. This helped greatly. Thanks.
LikeLike
you are welcome and thanks for your comment. =)
LikeLike