- 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.
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 ...
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().
IE has many unexpected behaviors~ i wish it will be extinct soon… =P
I know this is an old post, but we still have some users who have XP machines with IE7. This helped greatly. Thanks.
you are welcome and thanks for your comment. =)