Count number of words in string using JavaScript

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

    You can use split and add a wordcounter to the String prototype:

    String.prototype.countWords = function(){
      return this.split(/\s+/).length;
    }
    
    'this string has five words'.countWords(); //=> 5
    

    If you want to exclude things like ... or - in a sentence:

    String.prototype.countWords = function(){
      return this.split(/\s+\b/).length;
    }
    
    'this string has seven ... words  - and counting'.countWords(); //=> 7
    

提交回复
热议问题