javascript substring javascript substring javascript javascript

javascript substring


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.


You have three options in Javascript:

//slice//syntax: string.slice(start [, stop])"Good news, everyone!".slice(5,9); // extracts 'news'//substring //syntax: string.substring(start [, stop])"Good news, everyone!".substring(5,9); // extracts 'news'//substr//syntax: string.substr(start [, length])"Good news, everyone!".substr(5,4); // extracts 'news'


Check the substring syntax:

substring(from, to)

from Required. The index where to start the extraction. First character is at index 0

to Optional. The index where to stop the extraction. If omitted, it extracts the rest of the string

I'll grant you it's a bit odd. Didn't know that myself.

What you want to do is

alert('helloworld'.substring(5, 7));