jQuery字符和单词计数

这是一个非常简单的问题。 jQuery是否可以获取一个元素,并计算该元素中的单词和字符数(不是textarea或输入)并在HTML文档中回显它? 我能想到的唯一可行的代码是:

document.write("$('.content').text().length;") 

我真的很擅长jQuery,但我正在努力学习它。 如果有人可以提供脚本,这将是有帮助的。

 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" ); 

在拆分之前运行替换以消除标点符号,并使用正则表达式运行拆分以处理新行,制表符和单词之间的多个空格。

编辑添加了文本(…)位来写入节点,作为另一个答案的注释中指定的OP。

编辑你仍然需要将它包装在一个函数中,使其在页面加载后工作

 $( function(){ 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" ); }); 

否则它会在页面上呈现任何内容之前运行

  We have here 8 words and 35 chars ​ var text = $('#elementId').text(); var charsLength = text.length; //35 var wordsCount = text.split(' ').length; //8 

现场演示