the most darndest thing! the following code prints out 'llo' instead of the expected 'wo'. i get such surprising results for a few other numbers. what am i missing here?
alert('helloworld'.substring(5, 2));
the most darndest thing! the following code prints out 'llo' instead of the expected 'wo'. i get such surprising results for a few other numbers. what am i missing here?
alert('helloworld'.substring(5, 2));
The code above is wrong because the first value is the start point to the end point.E.g move from char 5 which is
o
and go to char 2 which is thel
so will getllo
So you have told it to go backwards.What yuou want is
This is What i have done,
You're confusing
substring()
andsubstr()
:substring()
expects two indices and not offset and length. In your case, the indices are 5 and 2, ie characters 2..4 will be returned as the higher index is excluded.Check the
substring
syntax:I'll grant you it's a bit odd. Didn't know that myself.
What you want to do is
See syntax below:
If
indexA > indexB
, thesubstring()
function acts as if arguments were reversed.Consider documentation here: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/substring
You have three options in Javascript: