Javascript 计算单词和字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14010446/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Count Words and Characters
提问by user1919937
I've been looking to add a word and character count to a textarea using jQuery although all I've found are plugins to limit characters and words.
我一直在寻找使用 jQuery 向文本区域添加单词和字符数的方法,尽管我发现的只是用于限制字符和单词的插件。
I would like to update in real-time, so that every time a user adds a character, or a word, the counter updates.
我想实时更新,这样每次用户添加一个字符或一个词时,计数器都会更新。
Is there a simple way to check for words and characters?
有没有一种简单的方法来检查单词和字符?
回答by Roko C. Buljan
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 wc = wordCount(this.value);
result.innerHTML = (`
<br>Characters (no spaces): ${wc.charactersNoSpaces}
<br>Characters (and spaces): ${wc.characters}
<br>Words: ${wc.words}
<br>Lines: ${wc.lines}
`);
});
<textarea id="text" cols="30" rows="4"></textarea>
<div id="result"></div>
回答by ATOzTOA
char_count = $("#myTextArea").val().length;
word_count = $("#myTextArea").val().split(" ").length;
回答by Techie
回答by Syed Osama
jQuery(document).ready(function(){
var count = jQuery("#textboxid").text().length;
});
回答by TheZuck
W/O jQuery:
无 jQuery:
this.innerHTML gives you the textarea content.
this.innerHTML.length gives you the number of characters.
With jQuery:
使用 jQuery:
$(this).html()
etc.
等等。
I'm sure you can come up with a simple word counting algorithm.
我相信你可以想出一个简单的字数统计算法。

