Ad

Javascript Substring Comparison; Am I Crazy?

- 1 answer

From my understanding, JavaScript's substring methods takes two parameters: first one is the index from where to start, and the second is the end point (non-index type counting, aka number of chars not 0-starting) which does not include the end-point char. Following this logic, I ran two examples:

This first example bellow worked as expected, I counted 13 chars because the 13th char was the end point and was not going to be included.

// goal was to print "Melbourne is"
alert("Melbourne is great".substring(0,13));

This example however failed. In this example I also stopped my count at the end point because I expected it not to be counted.

//goal was to print "Jan"
alert("January".substring(0,4)); 

Where is my understanding flawed?

Ad

Answer

The reason why you are going crazy is because the function

alert("Melbourne is great".substring(0,13)); 
//prints Melbourne_is_ not Melbourne_is

Notice the space after

Don't go crazy! :)

Ad
source: stackoverflow.com
Ad