Difference is Regex shorthand

Can someone please explain the difference between /\s/ and /\w/ or /\S/ and /\W/ ?

Here’s the code in question :

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


/\s/ matches any whitespace (space, tab, returns, etc.)
/\S/ matches anything not a whitespace
/\w/ matches anything a “word” character (letter, number, underscore)
/\W/ matches anything not a “word” character

That I understand, sort of. In the above, /\W/ does the same as /\s/ and /\S/ the same as /\w/. My question is what makes choosing one over the other any different if the outcome will be the same?

No, /\W/ and /\s/ are not the same. They are close but not the same. “Not a ‘word’ character” and “whitespace” are not the same thing. Close but not the same. There are plenty of characters that are not word characters that are also not whitespace, for example:


All of those characters will be matched by /\W/ and not /\s/. And those are just the characters in a regular keyboard.

They are just two different ways to refer to characters that overlap somewhat. Which you use depends on what you need.

There are maybe about 20 space characters defined, possibly a lot more (actual exact number seems to be unknown).
There are maybe 15,000-20,000 non-word characters (again, actual exact number seems to be unknown).

(this is assuming Unicode is being used)

> /\s/u.test("💩")
false # poo is not a space
> /\W/u.test("💩")
true # poo is a non-word character


> /\w/u.test("💩")
false # poo is not a word character
> /\S/u.test("💩")
true # poo is a non-space character

Thank you both. it makes complete sense now.