计算单词和字符

时间:2012-12-23 11:05:39

标签: javascript jquery html

我一直在寻找使用jQuery为textarea添加单词和字符数,尽管我发现所有内容都是限制字符和单词的插件。

我想实时更新,以便每次用户添加字符或单词时,计数器都会更新。

有没有简单的方法来检查单词和字符?

5 个答案:

答案 0 :(得分:49)

function wordCount( val ){
    var wom = val.match(/\S+/g);
    return {
        charactersNoSpaces : val.replace(/\s+/g, '').length,
        characters         : val.length,
        words              : wom ? wom.length : 0,
        lines              : val.split(/\r*\n/).length
    };
}


var textarea = document.getElementById("text");
var result   = document.getElementById("result");

textarea.addEventListener("input", function(){
  var v = wordCount( this.value );
  result.innerHTML = (
      "<br>Characters (no spaces):  "+ v.charactersNoSpaces +
      "<br>Characters (and spaces): "+ v.characters +
      "<br>Words: "+ v.words +
      "<br>Lines: "+ v.lines
  );
}, false);
<textarea id="text"></textarea>
<div id="result"></div>

jsFiddle demo

答案 1 :(得分:8)

char_count = $("#myTextArea").val().length;
word_count = $("#myTextArea").val().split(" ").length;

答案 2 :(得分:0)

var txt = $('.content')[0].text()
  , charCount = txt.length
  , wordCount = txt.replace( /[^\w ]/g, "" ).split( /\s+/ ).length
  ;
$( '#somwhereInYourDocument' ).text( "The text had " + charCount + " characters and " + wordCount +" words" );

Read more

答案 3 :(得分:-1)

W / O jQuery:

this.innerHTML gives you the textarea content.  
this.innerHTML.length gives you the number of characters.

使用jQuery:

$(this).html()

我相信你可以想出一个简单的字数统计算法。

答案 4 :(得分:-1)

jQuery(document).ready(function(){
    var count = jQuery("#textboxid").text().length;
});