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
Explanation:
- The function
countWordsOrSpaces
takes two parameters:input
(the string to be counted) andcountType
(specifying whether to count words or spaces). - Inside the function, it checks the value of
countType
using an if-else statement. - 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. - 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. - If
countType
is neither'words'
nor'spaces'
, it returns an error message'Invalid count type'
. - Examples demonstrate both word counting and space counting scenarios along with an example of an invalid count type.
Top comments (0)