Match Whitespace - Why doesn't \s* work as well as \s+?

Tell us what’s happening:

  1. (*) = 0 or more matches.
  2. (+) = 1 or more matches.

Why shouldn’t either character behave in the same way?

I did test these in CodePen and \s+ returns all the whitespace in a string while \s* returned all the characters as “” and white space as " " plus one additional “”. What is \s* tracking as the last “”?

Your code so far

let sample = "Whitespace is important in separating words";
let countWhiteSpace = /\s+/g; // Change this line
let result = sample.match(countWhiteSpace);

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36.

Link to the challenge:

There are 0 whitespace characters between the letters, so they count as a match for /\s*/g. There’s also 0 whitespace characters right before the very first and right after the very last letter of the string.

Hi @kevcomedia,

let sample = “h h”;
let countWhiteSpace = /\s*/g; // Change this line
let result = sample.match(countWhiteSpace);
//["", " ", “”, “”]

  1. “” : 0 white space before the first character of the string
  2. " " : 1 white space between the characters
  3. “” : 0 white space
  4. “” : 0 white space after the last character of the string

Shouldn’t the result return ["", " ", “”]?

I see what you mean. It seems that it also captures the empty string between spaces and the next letter. See In particular the dashed line after the blue highlight in the string

1 Like

That’s interesting! can you share your pen?

That’s a pretty cool tool. This makes it so much easier to visualize.

It is interesting though that /\s*\ of “h h” will find 0 whitespace before the 2nd h but not after the 1st h.