jQuery字符和字数统计 [英] jQuery character and word count

查看:110
本文介绍了jQuery字符和字数统计的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个非常简单的问题. jQuery是否有可能获得一个元素,并计算该元素(不是文本区域或输入)中的单词和字符数,并在HTML文档中将其回显?我能想到的唯一可行的代码是:

This is a really simple question. Is it possible for jQuery to get an element, and count the number of words AND characters in that element (not a textarea or input) and echo it out on a HTML document? The only code that I could think of that may work is:

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

我真的很讨厌jQuery,但是我正在尝试学习它.如果有人可以提供脚本,那会有所帮助.

I'm really bad at jQuery, but I'm trying to learn it. If anyone could provide a script, that'd be helpful.

推荐答案

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

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

Running replace before split to get rid of punctuation, and running split with a regular expression to deal with new lines, tabs and multiple spaces in between words.

EDIT 添加了text(...)位以写入节点,作为对另一个答案的注释中指定的OP.

EDIT added the text( ... ) bit to write to a node, as the OP specified in a comment to another answer.

编辑,您仍然需要将其包装在一个函数中,以使其在页面加载后可以正常工作

EDIT you still need to wrap it in a function to make it work after page load

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

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

Otherwise it runs before anything has been rendered on the page

这篇关于jQuery字符和字数统计的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆