Count number of words in string using JavaScript

后端 未结 5 1439
爱一瞬间的悲伤
爱一瞬间的悲伤 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 22:06

    I would prefer a RegEx only solution:

    var str = "your long string with many words.";
    var wordCount = str.match(/(\w+)/g).length;
    alert(wordCount); //6

    The regex is

    \w+    between one and unlimited word characters
    /g     greedy - don't stop after the first match
    

    The brackets create a group around every match. So the length of all matched groups should match the word count.

提交回复
热议问题