JavaScript: Count Words in a String

If you have a String object in JavaScript and you want to know the number of words it has, you can achieve this in various ways, lets see some of the code examples.

Example 1: Reading textarea data and finding the number of words in it.

<textarea id="myData" onBlur="getWordCount();"></textarea>
<div id="count"></div>

function getWordCount() {
 var myString = document.getElementById("myData").innerHTML;
 document.getElementById("count").innerHTML = myString.split(" ").length;
JavaScript String Word Count Example
JavaScript String Word Count Example

As you can see in the above example we have called a function onBlur of a textarea and read the text as a variable and then called two operations over it. First, we have done split based on space to get the array of words and then used length to get the count.

In the first example there are many ways we can go wrong. It's always better to use the trim() function along with the first example as there might be cases where the first and the last text in the string are spaces and we may get the wrong count, also what if there are multiple spaces between two words.

Example 2: Using regular expressions (RegEx)

Using regular expression is another way of knowing the number of words in a string, lets see an example,

var string = 'This is some random String to get its connt';



Have Questions? Post them here!
Try Out Code2care Dev Tools:


Android Java Linux Microsoft Google Python macOS Notepad++ Microsoft Teams CSS PHP SharePoint Html Linux C Programs Bootstrap jQuery Sublime Android Studio Facebook Eclipse WhatsApp News MySQL Json HowTos JavaScript FTP S3


Code2care is an initiative to publish and share varied knowledge in programming and technical areas gathered during day-to-day learnings and development activities.

Students and Software Developers can leverage this portal to find solutions to their various queries without re-inventing the wheel by referring to our easy to understand posts. Technical posts might include Learnings, Tutorials, Trouble-Shooting steps, Video Tutorials, Code Snippets, How Tos, Blogs, Articles, etc.
🎉 We are celebrating the 10th years of Code2care! Thank you for all your support! We hope we made a difference.
We strong support Gender Equality & Diversity.

We stand in solidarity with Ukraine - Make a donation to UNHCR -