Count number of words in string using JavaScript

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

    This is the best solution I've found:

    function wordCount(str) { var m = str.match(/[^\s]+/g) return m ? m.length : 0; }

    This inverts whitespace selection, which is better than \w+ because it only matches the latin alphabet and _ (see http://www.ecma-international.org/ecma-262/5.1/#sec-15.10.2.6)

    If you're not careful with whitespace matching you'll count empty strings, strings with leading and trailing whitespace, and all whitespace strings as matches while this solution handles strings like ' ', ' a\t\t!\r\n#$%() d ' correctly (if you define 'correct' as 0 and 4).

提交回复
热议问题