2017-07-12 9 views
0

Ich kann nicht herausfinden, warum meine Schleife nicht jedes Auftreten von myName in textToSearch finden kann. Es kann nur ein Vorkommen finden, wenn es in der Nähe von textToSearch steht.Suche nach einer Zeichenfolge innerhalb einer anderen mit For-Schleife

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

Antwort

2

Sie müssen i-i + myName.length String.

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 gibt es bessere Möglichkeiten Auftreten

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

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

0

Eine andere Lösung indexOf zu verwenden, ist zu zählen. Es wird ein Offset als zweiter Parameter benötigt.

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."); 
} 
Verwandte Themen