javascript tutorial - [Solved-5 Solutions] Difference between substr and substring - javascript - java script - javascript array



Problem:

What is the difference between substr and substring?

Solution 1:

The difference is in the second argument. The second argument to substring is the index to stop at (but not include), but the second argument to substr is the maximum length to return. Links?

Solution 2:

substr takes parameters as (from, length). substring takes parameters as (from, to).

alert("abc".substr(1,2)); // returns "bc"
alert("abc".substring(1,2)); // returns "b"
click below button to copy the code. By JavaScript tutorial team
  • We can remember substring takes indices, as does yet another string extraction method, slice .
  • When starting from 0 we can use either method.

Solution 3:

  • Another gotcha we recently came across is that in IE 8, "abcd".substr(-1) erroneously returns "abcd", whereas Firefox 3.6 returns "d" as it should. slice works correctly on both.

Solution 4:

  • substr() accepts a negative starting position as an offset from the end of the string. substring()does not.
  • From MDN
  • If start is negative, substr() uses it as a character index from the end of the string.
  • So to sum up the functional differences:
  • substring(begin-offset, end-offset-exclusive) where begin-offset is 0 or greater
  • substr(begin-offset, length) where begin-offset may also be negative

Solution 5:

  • The difference is second parameter. Their second parameters, while both numbers, are expecting two different things:
  • When using substring the second parameter is the first index not to include:
var s = "string";
s.substring(1, 3); // would return 'tr'

var s = "another example";
s.substring(3, 7); // would return 'ther'
click below button to copy the code. By JavaScript tutorial team

When using substr the second parameter is the number of characters to include in the substring:

var s = "string";
s.substr(1, 3); // would return 'tri'

var s = "another example";
s.substr(3, 7); // would return 'ther ex'

click below button to copy the code. By JavaScript tutorial team

Related Searches to javascript tutorial - Difference between substr and substring