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 substring() method extracts characters, between two indices (positions), from a string, and returns the substring. The substring() method extracts characters from start to end (exclusive). The substring() method does not change the original string.
The difference between substring() and substr()The two parameters of substr() are start and length , while for substring() , they are start and end . substr() 's start index will wrap to the end of the string if it is negative, while substring() will clamp it to 0 .
To remove a substring from a string, call the replace() method, passing it the substring and an empty string as parameters, e.g. str. replace("example", "") . The replace() method will return a new string, where the first occurrence of the supplied substring is removed.
substr(…) is not strictly deprecated (as in “removed from the Web standards”), it is considered a legacy function and should be avoided when possible. It is not part of the core JavaScript language and may be removed in the future. If at all possible, use the substring() method instead.
You're confusing substring()
and substr()
: 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With