Find Whitespace with Regular Expressions

Tell us what’s happening:

even if I put the expression as var expression = / /g; (WORKED FOR ME)
not sure what’s the use of \s+ here

Your code so far

// Setup
var testString = "How many spaces are there in this sentence?";

// Only change code below this line.

var expression = /\s+/g;  // Change this line

// Only change code above this line

// This code counts the matches of expression in testString
var spaceCount = testString.match(expression).length;

Your browser information:

Your Browser User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:56.0) Gecko/20100101 Firefox/56.0.

Link to the challenge:
https://www.freecodecamp.org/challenges/find-whitespace-with-regular-expressions

\s is a character class which means whitespace, and + means one or more of the proceeding character, so while / /g may work for that example, if you had two or more spaces in the test string right after one another, they would be separate matches, whereas /\s+/g would show the two or more spaces as a single match.

2 Likes