How to Count the Number of Spaces in a String Using JavaScript?

Estimated read time 1 min read

To count the number of spaces in a string using JavaScript, you can use the split() method to convert the string into an array of characters, and then use the filter() method to create a new array with all elements that match the space character. Finally, you can use the length property to determine the number of elements in that new array. Here’s an example:

function countSpaces(str) {
  return str.split("").filter(c => c === " ").length;
}

const sentence = "Count the number of spaces in this sentence.";
const count = countSpaces(sentence);
console.log(`The number of spaces in the sentence is: ${count}.`);

In the example above, the countSpaces function takes a string as an argument. The split() method is used to convert the string sentence into an array of characters using an empty string as a separator. The filter() method is then used to create a new array with all elements that match the space character " ", and the length property is used to determine the number of elements in that array, which represents the number of spaces in the original string. The result is logged to the console.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply