DEV Community

Avnish
Avnish

Posted on

Count the Words or Spaces in a String in JavaScript

Here is a JavaScript code snippet that counts either the words or spaces in a given string. Below are 5 examples along with explanations and outputs for each.

// Function to count words or spaces in a string
function countWordsOrSpaces(input, countType) {
    if (countType === 'words') {
        // Counting words
        const words = input.trim().split(/\s+/);
        return words.length;
    } else if (countType === 'spaces') {
        // Counting spaces
        const spaces = input.trim().split(/\S/).length - 1;
        return spaces;
    } else {
        return 'Invalid count type';
    }
}

// Example 1: Counting words
const example1 = "Hello world";
console.log("Example 1 - Counting words:", countWordsOrSpaces(example1, 'words')); // Output: 2

// Example 2: Counting spaces
const example2 = "Hello world";
console.log("Example 2 - Counting spaces:", countWordsOrSpaces(example2, 'spaces')); // Output: 1

// Example 3: Counting words
const example3 = "   Hello     world    ";
console.log("Example 3 - Counting words:", countWordsOrSpaces(example3, 'words')); // Output: 2

// Example 4: Counting spaces
const example4 = "   Hello     world    ";
console.log("Example 4 - Counting spaces:", countWordsOrSpaces(example4, 'spaces')); // Output: 5

// Example 5: Invalid count type
const example5 = "Hello world";
console.log("Example 5 - Invalid count type:", countWordsOrSpaces(example5, 'letters')); // Output: Invalid count type
Enter fullscreen mode Exit fullscreen mode

Explanation:

  1. The function countWordsOrSpaces takes two parameters: input (the string to be counted) and countType (specifying whether to count words or spaces).
  2. Inside the function, it checks the value of countType using an if-else statement.
  3. If countType is 'words', it trims the input string to remove leading and trailing spaces, then splits the string using a regular expression (/\s+/) which matches one or more whitespace characters. The resulting array's length is returned as the count of words.
  4. If countType is 'spaces', it trims the input string and splits it using a regular expression (/\S/) which matches any non-whitespace character. By subtracting 1 from the length of the resulting array, we get the count of spaces.
  5. If countType is neither 'words' nor 'spaces', it returns an error message 'Invalid count type'.
  6. Examples demonstrate both word counting and space counting scenarios along with an example of an invalid count type.

Top comments (0)