开发者

read number of charaters in HTML text using javascript

开发者 https://www.devze.com 2022-12-15 02:13 出处:网络
suppose i am getting HTML text in myJavaScript function as var TEMP= result.data; where result.data=\'<p>BODY&nbsp;Article By Archie(Used By Story Tool)</p>\';

suppose i am getting HTML text in my JavaScript function as

var TEMP= result.data;

where result.data='<p>BODY&nbsp;Article By Archie(Used By Story Tool)</p>';

i have done this:

            var e = document.createElement("span");
            e.innerHTML = TEMP;
            var text = e.innerText;
            var chara开发者_如何学GocterCount = text.length;                    
            var wordCount = text.match(/\b\w/g).length;

but this code doesn't work in mozilla firefox i have also tried o.k.w s code but didn't work in mozilla

and i also need the number of words i want to read the number of characters in TEMP,

and while doing that i want to skip HTML tags and html keywords (ex. &nbsp;)

pls help

and important this should work on mozilla firefox browser.


Tested the codes below on IE8/FF3.5/Chrome.
'<p>BODY&nbsp;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");
}


You can do this (this is using jQuery, but the same can be done without it):

var element = $('<p>BODY&nbsp;Article By Archie(Used By Story Tool)</p>');
var length = element.get(0).textContent.length;

You will get the length of text without tags or HTML entities

0

精彩评论

暂无评论...
验证码 换一张
取 消