Borislav Hadzhiev
Reading timeยท3 min
Photo from Unsplash
String.trim()
To count the words in a string:
String.split()
method to split the string into an array of words.length
property on the array.length
property will return the number of words in the string.function countWords(str) { const arr = str.split(' '); return arr.filter(word => word !== '').length; } console.log(countWords('bobby hadz com')); // ๐๏ธ 3 console.log(countWords('This is a long string')); // ๐๏ธ 5
We created a reusable function that takes a string as a parameter and returns the number of words in the string.
We used the String.split() method to split the string on each space.
The method returns an array containing the words in the string.
// ๐๏ธ ['hello', 'world'] console.log('hello world'.split(' ')); // ๐๏ธ [ 'bobby', 'hadz', 'com' ] console.log('bobby hadz com'.split(' '));
// ๐๏ธ ['hello', '', 'world'] console.log('hello world'.split(' ')); // ๐๏ธ ['one', '', 'two', '', 'three'] console.log('one two three'.split(' '));
We can use the Array.filter method to make sure we don't count empty strings as words.
filter
method enables us to remove the empty strings before accessing the length
property on the array.The function we passed to the filter()
method gets called with each element in
the array.
function countWords(str) { const arr = str.split(' '); return arr.filter(word => word !== '').length; } console.log(countWords('bobby hadz com')); // ๐๏ธ 3 console.log(countWords('This is a long string')); // ๐๏ธ 5
filter()
method returns.We check if each element is NOT equal to an empty string and return the result.
const arr = ['one', '', 'two', '']; const filtered = arr.filter(element => element !== ''); // ๐๏ธ ['one', 'two'] console.log(filtered);
The last step is to access the length
property on the array to get the word
count.
Alternatively, you can use the String.trim()
method.
String.trim()
#To count the words in a string:
String.trim()
method to trim the string.String.split()
method to split the string by one or more spaces.length
property on the result.function countWords(str) { return str.trim().split(/\s+/).length; } console.log(countWords('bobby hadz com')); // ๐๏ธ 3 console.log(countWords('This is a long string')); // ๐๏ธ 5
We used the String.trim() method to remove any leading and trailing whitespace from the string.
console.dir(' abc '.trim()); // ๐๏ธ "abc"
The next step is to use the String.split()
method to split the string by one
or more consecutive spaces.
We passed a regular expression to the String.split()
method.
function countWords(str) { return str.trim().split(/\s+/).length; }
The forward slashes / /
mark the beginning and end of the regular expression.
The \s
special character matches spaces, tabs and newlines.
The plus +
matches the preceding item one or more times (spaces).
In its entirety, the regular expression matches one or more consecutive spaces.
This way, we can be sure that we won't get multiple words if the string contains multiple spaces next to one another.
If you ever need help reading a regular expression, check out this regular expression cheatsheet by MDN.
It contains a table with the name and the meaning of each special character with examples.
To count the words in a textarea
element:
value
property on the textarea
element.length
property to get the word count.Here is the HTML for the example in the article.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <textarea id="textarea" cols="30" rows="10"></textarea> <p> Number of words: <span id="word-count"></span> </p> <button id="btn">Count words</button> <script type="module" src="index.js"></script> </body> </html>
And here is the related JavaScript code.
function countWords(str) { const arr = str.split(' '); return arr.filter(word => word !== '').length; } const button = document.getElementById('btn'); button.addEventListener('click', () => { const textarea = document.getElementById('textarea'); const wordCount = countWords(textarea.value); console.log(wordCount); const span = document.getElementById('word-count'); span.innerHTML = wordCount; });
Every time the button is clicked, we log how many words are written in the
textarea
element and show the result using a span
element.
We added a click event listener to the button element, so every time it is clicked, a function is invoked.
We used the value
property to get the value of the textarea
element and used
the previous function to get the word count.
The last step is to write the result to the screen by using the innerHTML
property on the span
element.