Reputation: 95
Currently going through different exercises over string variables. Right now, the current exercises deals with string methods. This is the variable that I'm working on.
var searchString = 'Lets search through this search string for the word, search';
What I did first was use this basic search method.
var searchIndex = searchString.search('search');
The result was a value of 5 returned to show the position of the first match. My question is, how do I go finding the second time search comes up in that string variable? How could I find the final time search comes up in the string variable?
Also, is it possible to use the search method to find all three times search came up at once and return all three?
Thanks in advance, everyone.
Kenneth
Upvotes: 1
Views: 33
Reputation: 2672
You can search like this:
var searchString = 'Lets search through this search string for the word, search';
function FindAllIndices(source, elem) {
var indices = [];
for(var pos = source.indexOf(elem); pos !== -1; pos = source.indexOf(elem, pos + 1)) {
indices.push(pos);
}
return indices;
}
console.log(FindAllIndices(searchString, "search"));
Upvotes: 1