1

http://stackoverflow.com/questions/askhttp://stackoverflow.com/questions/ask私は正規表現が苦手です。私が望むのは、文字列に http という単語が 2 回含まれているかどうかを確認することです。

ありがとう。

4

5 に答える 5

2

正規表現は必要ありません。String.indexOfを利用して単語カウントを実行する、このような小さな関数を使用できます。

編集:おそらく「単語数」は悪い説明であり、「パターン一致」の方が良いでしょう

Javascript

var testString = "http://stackoverflow.com/questions/askhttp://stackoverflow.com/questions/ask",
    testWord = "http";

function wc(string, word) {
    var length = typeof string === "string" && typeof word === "string" && word.length,
        loop = length,
        index = 0,
        count = 0;

    while (loop) {
        index = string.indexOf(word, index);
        if (index !== -1) {
            count += 1;
            index += length;
        } else {
            loop = false;
        }
    }

    return count;
}

console.log(wc(testString, testWord) > 1);

jsfiddleについて

于 2013-06-12T17:17:03.513 に答える