我无法弄清楚为什么我的循环无法在myName
中找到textToSearch
的每一次出现。如果它接近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);
}
答案 0 :(得分:2)
您需要从i
子串到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有更好的方法来计算发生次数
var textToSearch = "Aaron blue red Aaron green Aaron yellow Aaron";
console.log((textToSearch.match(/Aaron/g) || []).length)
答案 1 :(得分:0)
另一种解决方案是使用indexOf
。它将偏移量作为第二个参数。
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.");
}