0

まず第一に、私はjavascriptやjqueryが得意ではないので、私がいつも知らないことをするように、最初にインターネットで検索することを考えました。でも、質問が見つからなかったので、ここで助けを求めようと思いました。助けていただければ幸いです。

私が質問を始めたとき、このウェブサイトは私の研究を共有するように私に言いました、しかし私は何を共有するべきかを持っていません。

私の質問は、「javascriptまたはjqueryを使用して、特定の単語が1つのテキストエリアに何回書き込まれているのかを見つける方法」です。

それがjavascriptまたはjqueryで実行できるかどうかはわかりません。そのため、両方を作成しました。

ありがとう

4

3 に答える 3

3

単純な概念実証:

$('#test').keyup(function(e){
    var v = $(this).val(), // the current value of the textarea,
        w = v.split(/\s/), // the individual words
        needle = 'img', // what you're looking for
        c = 0; // the count of that particular word
    for (var i=0,len=w.length;i<len;i++){
        // iterating over every word
        if (w[i] === needle){
        // if a given word is equal to the word you're looking for
        // increase the count variable by 1
            c++;
        }
    }
    // set the text of the 'output' element to be the count of occurrences
    $('#output').text(c);
});

JSフィドルデモ

参照:

于 2013-03-22T12:41:48.370 に答える
2

.match()を使用して、文字列内の正規表現を照合できます。

var str = "This my wordy string of words";
console.log(str.match(/word/g).length); // Prints 2 as it's matched wordy and words
console.log(str.match(/word\b/g).length); // Prints 0 as it has NOT matched wordy and words due to the word boundary

これらも大文字と小文字を区別します。追加のオプションについては、正規表現を調べてください。

于 2013-03-22T12:44:31.357 に答える
2

試す

var regex = new RegExp('\\b' + word + '\\b', 'gi');
var count = string.match(regex).length
于 2013-03-22T12:48:14.120 に答える