Counting Words in String


Function to count the number of words in a string:

You can create a JavaScript function to count the number of words in a string by splitting the string into words and then counting the number of resulting elements. Here's how you can implement it:

js Copy Code
function countWords(str) {
    // Remove leading and trailing whitespaces
    str = str.trim();
    // Split the string into words based on whitespaces
    const words = str.split(/\s+/);
    // Return the number of words
    return words.length;

// Example usage:
const sentence = "The quick brown fox jumps over the lazy dog";
console.log(countWords(sentence)); // Output: 9


1. We use the 'trim()' method to remove leading and trailing whitespaces from the string to ensure accurate word count.

2. We split the string into words using the 'split()' method, which splits the string based on one or more whitespace characters ('\s+' regular expression).

3. We then return the length of the resulting array, which represents the number of words in the string.

You can use this 'countWords' function to count the number of words in any given string.

What's Next?

We actively create content for our YouTube channel and consistently upload or share knowledge on the web platform.