Hi! I'm Nathan Hoad


Javascript: Difference between substr and substring

Javascript has two string methods (substr and substring) that appear to be identical at first glance; they both return a substring from a given string. So what's the difference? 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'

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'

For more information on string functions, checkout Quirksmode's guide.

If I just made your day a little better then thank me with a coffee or maybe a a pizza