dexter
dexter

Reputation: 1207

read number of charaters in HTML text using javascript

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 characterCount = 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.

Upvotes: 0

Views: 201

Answers (2)

o.k.w
o.k.w

Reputation: 25800

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");
}

Upvotes: 2

Igor Zinov&#39;yev
Igor Zinov&#39;yev

Reputation: 3706

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

Upvotes: 1

Related Questions