1

だから、私は 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);
}
4

7 に答える 7

4

空白で文字列を 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について

注:同じことを行う他の解決策がいくつかあります。

于 2013-06-17T18:27:02.850 に答える
3

**

for(var i = 0; i < text.length ; i++){
    if(text[i] === "Z"){
        var getText = text.substring(i, i + myName.length);
        if(getText === myName)
        {
            for(var j = i; j < (myName.length + i); j++){
                hits.push(text[j]);
                }
            }
        }
    }

**

それは...簡単なものです。

于 2015-06-23T06:13:00.043 に答える
3

これらすべてを行う必要はありません。

次のコードであなたの名前を見つけてください

if(text.indexOf(myName) !== -1){
  console.log('Found');
}

それがあなたが見つけたい出現の総数である場合

var count = text.match(/Zachary/g).length; 
console.log(count)
于 2013-06-17T18:10:02.060 に答える