如何计算wysiwyg编辑器javascript中的字数

How to count the number of words in wysiwyg editor javascript?

本文关键字:javascript 编辑器 wysiwyg 何计算 计算      更新时间:2023-09-26

我正在使用所见即所得编辑器,在那里编写并保存了它。

我只想数一下我写了多少个字。

假设我已经写了"My Count is 4",那么它应该显示计数为13

并且在将其标记为粗体或斜体之后,计数应保持为13。

我用来计数的代码是jQuery(selector).text().length;

但它会将数据和html标签一起返回给我。

如果我在编辑器中用粗体写了"My Count is 4"。计数正在增加,因为它也在计算html <b></b>标记。

请帮我找到解决方案。

试试这样的东西:

// firstly we'll strip the html out
var myCode = jQuery('#getMe').html();
// strip out tags and line breaks
var cleanCode = myCode.replace(/<(?:.|'n)*?>/gm, '').replace(/('r'n|'n|'r)/gm,"").replace('&nbsp;','');
// then count as normal
var numChars = cleanCode.trim().length;

看看这个小提琴