Count the number of words in a string in JavaScript

It is quite an easy task to count the number of words in a given string with JavaScript. In this article, I will show you how to perform this task.

To count words from the string, we are going to create our own custom function. So below is the code to create our custom function that can perform our task:

function wordCount(str) {
    str = str.replace(/(^\s*)|(\s*$)/gi,"");
    str = str.replace(/[ ]{2,}/gi," ");
    str = str.replace(/\n /,"\n");
    count = str.split(' ').length;
    return count;
}

As you can see, in our function, we are taking a parameter. This parameter will be the string for which we want to count the words.

We are using regular expressions with the JavaScript string replace() method in a tricky way. First, we remove the spaces from the beginning as well as from the end.

After that, we converted multiple spaces into a single. Then excluding a new line with a start spacing.

Now we have a string that has single spaces inside words. In the end, the words join by comma and return the length. The length will be the total number of words available in the string.

Now let’s see some usage of our custom function below:

console.log(wordCount(" CodeSpeedy is a great platform for  self-learning"));  // 7
console.log(wordCount(" CodeSpeedy is a great platform for  self-learning. Everybody welcome here.  Learn yourself."));  //12

We will able to get the number of words for the string we pass to the function as an argument. All we need to do is just pass our string to the function at the time of calling it.

So, with that way, we can pass any sentence or even article as the string to our custom JavaScript function to count the number of words available in that content.

Also, read: Live word counter from HTML textarea in JavaScript

 

Leave a Reply

Your email address will not be published. Required fields are marked *