使用javascript读取HTML文本中的字符数 [英] read number of charaters in HTML text using javascript
问题描述
假设我在 JavaScript函数中获取HTML文本为
suppose i am getting HTML text in my JavaScript function as
var TEMP= result.data;
其中 result.data ='< p> BODY& nbsp;文章由Archie(故事工具使用)< / p>';
我做到了这一点:
var e = document.createElement("span");
e.innerHTML = TEMP;
var text = e.innerText;
var characterCount = text.length;
var wordCount = text.match(/\b\w/g).length;
但是这段代码在mozilla firefox中不起作用
i也试过 okw 代码,但在mozilla中无效
but this code doesn't work in mozilla firefox i have also tried o.k.w s code but didn't work in mozilla
我还需要单词数
i想读TEMP中的字符数,
and i also need the number of words i want to read the number of characters in TEMP,
在这样做时我想跳过 HTML标记和html关键字(例如& nbsp;
)
and while doing that i want to skip HTML tags and html keywords (ex.
)
请帮助
且重要这应该适用于 mozilla firefox 浏览器。
and important this should work on mozilla firefox browser.
推荐答案
在IE8 / FF3.5 / Chrome上测试下面的代码。
'< p> BODY& nbsp;文章由Archie(由故事工具使用)< / p>'
给我的字数为42。
Tested the codes below on IE8/FF3.5/Chrome.
'<p>BODY Article By Archie(Used By Story Tool)</p>'
gives me charater count of 42.
function getCharCount(str){
var d = document.createElement("div");
d.innerHTML = str;
if(d.textContent) //for FF and DOM3 compliant
alert(d.textContent.length);
else if(d.innerText) //for IE and others
alert(d.innerText.length);
else
alert("0");
}
这篇关于使用javascript读取HTML文本中的字符数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!