javascript substring

JavascriptStringSubstring

Javascript Problem Overview


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));

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

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'

Solution 3 - Javascript

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));

Solution 4 - Javascript

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 the l so will get llo So you have told it to go backwards.

What yuou want is

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

Solution 5 - Javascript

See syntax below:

str.substring(indexA, [indexB])

If indexA > indexB, the substring() function acts as if arguments were reversed.

Consider documentation here: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/substring

Solution 6 - Javascript

This is what I have done...

var stringValue = 'Welcome to India';

// if you want take get 'India' 
// stringValue.substring(startIndex, EndIndex)
   stringValue.substring(11, 16); // O/p 'India'

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionakula1001View Question on Stackoverflow
Solution 1 - JavascriptChristophView Answer on Stackoverflow
Solution 2 - JavascriptChiragView Answer on Stackoverflow
Solution 3 - JavascriptPekkaView Answer on Stackoverflow
Solution 4 - JavascriptAutomatedTesterView Answer on Stackoverflow
Solution 5 - JavascriptAlexandru DiacovView Answer on Stackoverflow
Solution 6 - JavascriptNayas SubramanianView Answer on Stackoverflow