How to count a number of words in given string in JavaScript?

JavascriptObject Oriented ProgrammingProgramming

Using regular expressions it is easy to count number of words in a given string in javascript. There are some steps to be followed to count number of words

Steps to follow

We know that a sentence or a phrase is made up of words that are separated with spaces in between and there are some instances in which the words are separated by 2 or more spaces. A developer must notice all these points while calculating no of words. 


Exclude the start and end spaces of a string. The following line of regex expression will remove the start and end spaces of the given string.



Try to reduce multiple spaces to a single space.

str.replace(/[ ]{2,}/gi," ");


Try to exclude a new line with a start spacing.

str.replace(/\n /,"\n");

After performing all the above mention steps we will have a string with a single spaced words. On splitting the resulted string using split() method the words are going to join by a comma instead of spaces. Now using length() method we can get the resulted word count as shown in the following example.


Live Demo

      function countWords(str) {
         str = str.replace(/(^\s*)|(\s*$)/gi,"");
         str = str.replace(/[ ]{2,}/gi," ");
         str = str.replace(/\n /,"\n");
         return str.split(' ').length;
      document.write(countWords("   Tutorix is one of the best E-learning   platforms"));


Published on 20-Jun-2019 18:56:25