Find number of spaces in a string using JavaScript

JavascriptWeb DevelopmentObject Oriented Programming

There exists more than one way of finding this using JavaScript like by using the split() method, by using the for loop, by mapping and filtering, by using regex.

The way that makes use of regex is by far the most efficient and most performant method than the others, especially for big chunks of text. So we will be using that to solve this problem.

Following is the code −

Example

console.log(("abc def rr tt".match(/ /g) || []).length);
console.log(("a f fe fg gsd f".match(/ /g) || []).length);

Note that we used an empty array with the OR operator to make sure that if the string does not contain any space instead of throwing error it should output 0.

Output

Output in the console will be −

3
5
raja
Published on 18-Aug-2020 07:14:43
Advertisements