我一直在寻找使用jQuery为textarea添加单词和字符数,尽管我发现所有内容都是限制字符和单词的插件。
我想实时更新,以便每次用户添加字符或单词时,计数器都会更新。
有没有简单的方法来检查单词和字符?
答案 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>
答案 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" );
答案 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;
});