0

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.

dexter
  • 1,207
  • 10
  • 26
  • 41

2 Answers2

2

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
  • 25,490
  • 6
  • 66
  • 63
  • 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 Dec 22 '09 at 13:58
  • Ah, I didn't know of that post. Thanks for the reference :) – o.k.w Dec 22 '09 at 14:41
  • 1
    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 Dec 23 '09 at 13:42
1

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
  • 3,676
  • 1
  • 33
  • 49
  • thanks for reply but i have an issue that the 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 Dec 23 '09 at 06:38
  • 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 = $('
    ' + result.data + '
    ');` The `div` wrapping is just to be sure that you have a single element wrapping all your code.
    – Igor Zinov'yev Dec 23 '09 at 08:51