views:

94

answers:

2

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.

+1  A: 

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

Igor Zinov'yev
thanks for reply but i have an issue thatthe html text would be bind to an object eg. var element= result.data;and now element will have html inside how to implement this ?
dexter
this gives an error
dexter
If I get it right, you want to create an element from an HTML code that you get from a response. In that case you just do it the same way: `var element = $('<div>' + result.data + '</div>');` The `div` wrapping is just to be sure that you have a single element wrapping all your code.
Igor Zinov'yev
+2  A: 

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");
}
o.k.w
Requisite reference on this trick you're doing: http://stackoverflow.com/questions/1359469/innertext-works-in-ie-but-not-in-firefox/1359822#1359822
Crescent Fresh
Ah, I didn't know of that post. Thanks for the reference :)
o.k.w
in FireFox its not working....duno the issue
dexter
it worked. thanksmy bad i commented earlier
dexter
Great! No worries!
o.k.w
I'd test for `textContent` first as it is the DOM 3 Core standard method. Also, better to use `if ('innerText' in d)` to check for the existence of the property as testing directly on the value will fail if the text is an empty string (which is falsy in JavaScript).
bobince
Very valid points you have there!
o.k.w