0

I'm on Codecademy and I am learning JavaScript. I'm on substrings and I get how to do them, but I wander why substrings extracts characters from indexA up to but not including indexB. Why does it include indexA, but only up to indexB?

Please use the best layman's term for this, considering I don't have that much knowledge in this language (I'm only familiar with HTML & CSS).

ErraticFox
  • 1,363
  • 1
  • 18
  • 30
  • could you provide som examples? – Marcus Brunsten Jan 02 '14 at 12:14
  • 1
    It has already been asked. http://stackoverflow.com/questions/11364533/why-are-slice-and-range-upper-bound-exclusive – donutboy Jan 02 '14 at 12:16
  • Isn't this a question that can be answer by just reading [documentation](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/substring)? Or maybe even the answer 'because it does'?. Why are you asking? Do you have a specific problem? – George Jan 02 '14 at 12:17

4 Answers4

1

That's because it's designed that way. Here's some documentation from MDN.

"Hello World".substring(0,5) //Hello

Simply saying

Get the substring starting with (and including) the character at the first index, and ending (but not including) the character at the second index.

Joseph
  • 117,725
  • 30
  • 181
  • 234
1
var longString = "this is a long string";
var substr1 = longString.substring(0, 4); //"this"
var substr2 = longString.substring(4, 8); //" is "

This makes sense because the second substring started from where the first left off, without copying the same letter twice in both substrings. It makes it more useful in loops, for example.

Also, as everyone keeps pointing out, because "it's defined that way..."

johnnycardy
  • 3,049
  • 1
  • 17
  • 27
0

Well, the method is defined in that way. Extracts from indexA up to indexB but not including.

MillaresRoo
  • 3,808
  • 1
  • 31
  • 37
0

In Javascript there are two different functions to extract a substring. One with length and other with index start and stop.

String.substring( from [, to ] )
String.substr( start [, length ] )

In all cases, the second argument is optional. If it is not provided, the substring will consist of the start index all the way through the end of the string.

Please go through this article to clear up.

http://www.bennadel.com/blog/2159-Using-Slice-Substring-And-Substr-In-Javascript.htm

Shiva Avula
  • 1,836
  • 1
  • 20
  • 29