Javascript – Negative substr() problem in Internet Explorer

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()

About these ads

2 thoughts on “Javascript – Negative substr() problem in Internet Explorer

  1. Daniel

    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().

    Reply

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s