だから、私は JavaScript の初心者です。私は今、Codeacedemy のチュートリアルで練習していて、テキストの文字列から自分の名前を見つけるプログラムを作成する必要がありました。しかし、自分に似た名前を使用すると、別の名前も返されることに気付きました。文字列内の正確な名前のみに一致するように、どのような方法を使用できますか、またはコードを改良するにはどうすればよいですか?
コードは次のとおりです。
/*jshint multistr:true */
var text = "Hello my name is Zachary Sohovich. I'm a 20 year old dude from Southern California and I love to code";
var myName = "Zachary";
var hits = [];
for (var i = 0; i < text.length; i++){
if (text[i] == 'Z') {
for (var j = i;j < (i + myName.length); j++) {
hits.push(text[j]);
}
}
}
if (hits === 0) {
console.log("Your name was not found!");
}
else {
console.log(hits);
}