【发布时间】:2013-02-07 04:30:50
【问题描述】:
我计算contenteditable 中的单词。我用空格分割它。当您输入新行时,问题就来了。在您添加空格之前,它不会计算您当前在新行上书写的单词。
最重要的是,在下面的示例中,如果您将示例文本分成两行,那么当您这样做时,它会“吃掉”一个单词:
我猜这个问题的存在是因为 HTML 元素之间没有空格:
<div>some things</div><div>are cool</div> 它的字符串是“some thingsare cool”。
这是我的代码:
function wordCount() {
var content_text = $('#post_content').text(),
char_count = content_text.length,
word_count = 0;
// if no characters, words = 0
if (char_count != 0)
word_count = content_text.replace(/[^\w ]/g, "").split(/\s+/).length;
$('.word_count').html(word_count + " words • " + char_count + " characters");
}
我尝试替换一些 HTML 标签:
word_count = content_text.replace(/ /g, " ").replace(/<div>/g, "<p>").replace(/<\/div>/g, "</p>").replace(/<\/p><p>/g, " ").split(/\s+/).length;
没有任何运气。无论是<p> 还是<div>,我都需要丢弃,有些浏览器在合并行时会添加&nbsp;。
有什么想法吗?谢谢!
编辑:
感谢下面杰斐逊的聪明方法,我设法解决了这个问题。出于某种原因,我必须在 word_count 上执行 -1 以显示正确的字数:
function wordCount() {
var content_div = $('#post_content'),
content_text,
char_count = content_div.text().length,
word_count = 0;
// if no characters, words = 0
if (char_count != 0)
content_div.children().each(function(index, el) {
content_text += $(el).text()+"\n";
});
// if there is content, splits the text at spaces (else displays 0 words)
if (typeof content_text !== "undefined")
word_count = content_text.split(/\s+/).length - 1;
$('.word_count').html(word_count + " words • " + char_count + " characters");
}
【问题讨论】:
-
sashok - 很好的问题。很详细。感谢您使用 jsfiddle
-
计数关闭,甚至没有按回车键:
console.log(content_text.replace(/[^\w ]/g, "").split(/\s+/));第一个索引是一个空字符串。
标签: javascript jquery html counter contenteditable