您可以String.split空格处的字符串以创建一个单词数组,然后根据您的测试字符串检查每个单词,从而防止子字符串中的匹配。(有一个替代循环while
)
Javascript
var text = "Hello my name is Zachary Sohovich. I'm a 20 year old dude from Southern California and I love to code",
myName = "Zachary",
hits = 0,
array = text.split(/\s/),
length = array.length,
i = 0;
while (i < length) {
if (myName === array[i]) {
hits += 1;
}
i += 1;
}
if (hits === 0) {
console.log("Your name was not found!");
} else {
console.log(hits);
}
在jsfiddle 上
或者,如果你真的想通过循环检查字符串来获得乐趣,那么你可以做这样的事情。
Javascript
var text = "Zachary Hello my name is Zachary Sohovich. I'm a 20 year old dude from ZacharySouthern California and I loZacharyve to code Zachary",
textLength = text.length,
myName = "Zachary",
nameLength = myName.length,
check = true,
hits = 0,
i = 0,
j;
while (i < textLength) {
if (check) {
if (i !== 0) {
i += 1;
}
j = 0;
while (j < nameLength) {
if (text.charAt(i + j) !== myName.charAt(j)) {
break;
}
j += 1;
}
if (j === nameLength && (/\s/.test(text.charAt(i + j)) || i + j === textLength)) {
hits += 1;
i += j;
}
}
i += 1;
check = /\s/.test(text.charAt(i));
}
if (hits === 0) {
console.log("Your name was not found!");
} else {
console.log(hits);
}
在jsfiddle 上
注意:还有许多其他可能的解决方案可以为您做同样的事情。