-2

Possible Duplicate:
What is the difference between substr and substring?

I just want to clarify this differences of:-

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

the above case both will return

ab

alert("abc".substr(1,2));
alert("abc".substring(1,2));

and the above case will return first bc and the second one b

so basically for the substr the second argument is the length it has to go? and for substring it will stop but not include??

Please correct me if I'm wrong because we will have a quiz today and I don't want to get this wrong again.

Community
  • 1
  • 1
Ali
  • 9,997
  • 20
  • 70
  • 105
  • 5
    You know there's a site called google, right? [first hit](http://www.bloggingdeveloper.com/post/substring-vs-substr-The-Difference-Between-JavaScript-String-Functions.aspx) – Elias Van Ootegem Apr 12 '12 at 14:23
  • @EliasVanOotegem Thank you for reminding me of that :) – Ali Apr 12 '12 at 14:23

3 Answers3

4

Yes, substr()'s second parameter is the length of the required substring while substring()'s is a character index, a fact which is pretty trivial to find via a web search.

What is less well-known is that substr() is non-standard (up to and including ECMAScript 5; ES3 and ES5 have non-normative sections on substr()) and had some bugs in older versions of IE. Also, slice() is preferable to substring() because it allows negative character indices, counted backwards from the end of the string:

alert( "Dandelion".slice(-4) ); // Alerts "lion"
Tim Down
  • 318,141
  • 75
  • 454
  • 536
1

Yes, substring goes to an index while substr goes a length.

jeremyharris
  • 7,884
  • 22
  • 31
1

As per the following link:

http://rapd.wordpress.com/2007/07/12/javascript-substr-vs-substring/

Substr takes a starting index and the length of the string you are trying to segment

Substring takes a starting index and the index up to which you want it to segment the string

Raul Marengo
  • 2,287
  • 1
  • 15
  • 10