var myStr = "I love chocolate and strawberry, love this and that as well, and again love walking along the street";
var newStr = myStr.substr(myStr.indexOf('love'), myStr.lastIndexOf('love'));
///" chocolate and strawberry, "; //this is the output
var myStr = "I love chocolate and strawberry, love this and that as well, and again love walking along the street";
var newStr = myStr.substr(myStr.indexOf('love'), myStr.lastIndexOf('love'));
console.log(newStr);
var myStr = "I love chocolate and strawberry, love this and that as well, and again love walking along the street";
var newStr = myStr.substr(myStr.indexOf('love'), myStr.lastIndexOf('love'));
///" chocolate and strawberry, "; //this is the output
var myStr = "I love chocolate and strawberry, love this and that as well, and again love walking along the street";
var newStr = myStr.substr(myStr.indexOf('love'), myStr.lastIndexOf('love'));
console.log(newStr);
How do I get the text between the the first word 'love' and the second word "love" which should be " chocolate and strawberry, "?
Share Improve this question asked Nov 4, 2016 at 17:47 user7083815user7083815 1-
1
String.indexOf()
supports second param,fromIndex
(doc). If you store the result of the firstindexOf
, just reuse it. – raina77ow Commented Nov 4, 2016 at 17:53
5 Answers
Reset to default 3Use String#substring
and String#indexOf
method with fromIndex argument.
var myStr = "I love chocolate and strawberry, love this and that as well, and again love walking along the street";
var str='love', ind = myStr.indexOf(str);
var newStr = myStr.substring(ind + str.length , myStr.indexOf(str,ind + 1));
console.log(newStr);
You can split your string with love
:) and look at the second item in array:
var newStr = myStr.split("love")[1];
I agreed with above answer, but if you want to know how to get the index of second "Love", you can pass the "startingPostion" in indexOf(), so it will look for word "Love" after the starting Position.
The problem you're experiencing is caused because the second index you're sending to the substring method is the beginning of the last word 'love' and not the end of it... If you'll add the length of the word 'love' to the second index, your code should work just fine.
Wrap split into a function for easy use.
Just call getTextBetween(splitOnString, middleTextDesired)
on your string.
splitOnString
is the text you want to look between.
middleTextDesired
is the number of middle text you want. 1
for 1st, 2
for 2nd, etc...
It's not a finished function as defensive checks are not added, but the idea is clear.
var myStr = "I love chocolate and strawberry, love this and that as well, and again love walking along the street";
String.prototype.getTextBetween = function(splitOn, middleTextDesired = 1) {
return this.split(splitOn)[middleTextDesired];
}
console.log(myStr.getTextBetween('love', 1));