views:

107

answers:

2

What is the difference between

alert("abc".substr(0,2));

and

alert("abc".substring(0,2));

They both seem to output “ab”.

+8  A: 

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?

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/substr

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/substring

Delan Azabani
Sounds like a common source of error. Good to know the difference. Found additional comments about this here: http://rapd.wordpress.com/2007/07/12/javascript-substr-vs-substring/
schnaader
+5  A: 

The first takes parameters as (from, length).
The second takes parameters as (from, to).

alert("abc".substr(1,2)); // returns "bc"
alert("abc".substring(1,2)); // returns "b"

Resources :

Colin Hebert