我不明白为什么我的循环无法找到 textToSearch
中出现的每个 myName
。如果它靠近 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);
}
最佳答案
您需要从 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);
}
顺便说一句,有更好的方法来计算出现次数
var textToSearch = "Aaron blue red Aaron green Aaron yellow Aaron";
console.log((textToSearch.match(/Aaron/g) || []).length)
关于javascript - 使用 for 循环查找另一个字符串中的一个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45057804/