internet explorer 9 - Count number of words in string using JavaScript -
i trying count number of words in given string using following code:
var t = document.getelementbyid('mso_contenttable').textcontent; if (t == undefined) { var total = document.getelementbyid('mso_contenttable').innertext; } else { var total = document.getelementbyid('mso_contenttable').textcontent; } counttotal = cword(total); function cword(w) { var count = 0; var words = w.split(" "); (i = 0; < words.length; i++) { // inner loop -- count if (words[i] != "") { count += 1; } } return (count); }
in code getting data div tag , sending cword()
function counting. though return value different in ie , firefox. there change required in regular expression? 1 thing show both browser send same string there problem inside cword()
function.
you can make clever use of replace() method although not replacing anything.
var str = "the long text have..."; var counter = 0; // lets loop through string , count words str.replace(/(\b+)/g,function (a) { // each word found increase counter value 1 counter++; }) alert(counter);
the regex can improved exclude html tags example
Comments
Post a Comment