Count number of words in string using JavaScript

后端 未结 5 1422
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-04 21:20

I am trying to count the number of words in a given string using the following code:

var t = document.getElementById(\'MSO_ContentTable\').textContent;

if (         


        
5条回答
  •  被撕碎了的回忆
    2021-01-04 21:57

    You can make a clever use of the replace() method although you are not replacing anything.

    var str = "the very long text you have...";
    
    var counter = 0;
    
    // lets loop through the string and count the words
    str.replace(/(\b+)/g,function (a) {
       // for each word found increase the counter value by 1
       counter++;
    })
    
    alert(counter);
    

    the regex can be improved to exclude html tags for example

提交回复
热议问题