A.Murph
A.Murph

Reputation: 3

Finding one string inside of another using for loop

I cannot figure out why my loop is unable to find every occurrence of myName in textToSearch. It can find only one occurrence if it is near the beginning of textToSearch.

var textToSearch = "Aaron blue red Aaron green Aaron yellow Aaron";
var myName = "Aaron";
var hits = [];
for(i = 0; i < textToSearch.length; i++){
   if(textToSearch.substring(i, myName.length) === myName){ 
     hits.push(textToSearch.substring(i, myName.length));
   }
}
if(hits.length === 0){
   console.log("Your name wasn't found!");
} else {
   console.log("Your name was found " + hits.length + " times.");
   console.log(hits);
}

Upvotes: 0

Views: 48

Answers (2)

Valentin Klinghammer
Valentin Klinghammer

Reputation: 1349

Another solution is to use indexOf. It takes an offset as a second parameter.

var textToSearch = "Aaron blue red Aaron green Aaron yellow Aaron";
var myName = "Aaron";
var hits = 0;
var lastIndex = 0;

while(lastIndex != -1){
   lastIndex = textToSearch.indexOf(myName, lastIndex);
   if (lastIndex != -1) {
     hits++;
     lastIndex++;
   } // Search at the next index
}

if(hits === 0){
   console.log("Your name wasn't found!");
} else {
   console.log("Your name was found " + hits + " times.");
}

Upvotes: 0

Yury Tarabanko
Yury Tarabanko

Reputation: 45121

You need to substring from i to i + myName.length.

var textToSearch = "Aaron blue red Aaron green Aaron yellow Aaron";
var myName = "Aaron";
var hits = [];
for(var i = 0; i < textToSearch.length; i++){
   if(textToSearch.substring(i, i + myName.length) === myName){ 
     hits.push(textToSearch.substring(i, i + myName.length));
   }
}
if(hits.length === 0){
   console.log("Your name wasn't found!");
} else {
   console.log("Your name was found " + hits.length + " times.");
   console.log(hits);
}

BTW there are better ways to count occurrence

var textToSearch = "Aaron blue red Aaron green Aaron yellow Aaron";

console.log((textToSearch.match(/Aaron/g) || []).length)

Upvotes: 2

Related Questions