jQuery字符和字数统计

编程入门 行业动态 更新时间:2024-10-21 18:36:35
本文介绍了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字符和字数统计

本文发布于:2023-11-11 07:08:20,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1577726.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符   字数   jQuery

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!