0

この関数で単語をより正確にカウントし、最も重要なこととして、編集可能な div 内の単語をカウントすることは可能ですか?

$(document).ready(function() {

$('.word_count').each(function() {
    var input = '#' + this.id;
    var count = input + '_count';
    $(count).show();
    word_count(input, count);
    $(this).keyup(function() { word_count(input, count) });
});

});

function word_count(field, count) {

var number = 0;
var matches = $(field).val().match(/\b/g);
if(matches) {
    number = matches.length/2;
}
$(count).text( number + ' word' + (number != 1 ? 's' : '') + ' aprox' );

}
4

3 に答える 3

0

私の個人的なライブラリから:

var s = "Is it possible to make this function to count words more accurately and most important, count the word inside a editable div?";
s = s.replace(/(^\s*)|(\s*$)/gi, "");
s = s.replace(/[ ]{2,}/gi, " ");
s = s.replace(/\n /, "\n");
var countresult = s.split(' ').length;
alert("The string:\""+s+"\" and the word count is "+countresult+".");

実際の例については、 http://jsfiddle.net/farondomenic/XAvh6/を参照してください。

于 2013-05-17T13:41:36.083 に答える
0

私は .split() メソッドを使用します。要素を取得して配列を作成します。非常に簡単で、コーディングが簡単です。アイデアが好きかどうかを知るために、これ以上の例は必要ないと思います。ご不明な点がございましたら、お気軽にお問い合わせください... W3 Schools の例

于 2013-05-17T13:41:41.800 に答える