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.

    <title>substr() problem in Internet Explorer</title>
    <script type="text/javascript">
      var testString = "0123456789";
      function showResult() {
        // Output: 23456789
        alert(testString.substr(2, 5));
        // Output: 23456
        // Output: 789
        alert(testString.substr(-5, 2));
        // Output: 56
  <body onload="javascript:showResult();">


It seems that everything is straight forward, but try the above HTML in the greatest browser which is called Internet Explorer, you will get

// 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)
// Output: 789
//alert(testString.substr(-5, 2));
alert(testString.slice(-5, (testString.length-5)+2));
// Output: 56


Done =)

Reference: Javascript: substr() v.s. substring()


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

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


  2. I know this is an old post, but we still have some users who have XP machines with IE7. This helped greatly. Thanks.


Leave a Reply

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

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

Facebook photo

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

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.