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 −
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 in the console will be −