Why does this regex → /(^|\s)\S/g find characters after whitespace characters?

Viewed 38

I'm unsure as to how the whitespace section works. This snippet comes from freecodecamp and it's given as a solution to a problem where you're supposed to make every first letter upper case.

Here is the full algorithm:

function titleCase(str) {
  return str
    .toLowerCase()
    .replace(/(^|\s)\S/g, L => L.toUpperCase());
}

And their explanation for the regex:

Regex explanation:

Find all non-whitespace characters (\S)
At the beginning of string (^)
Or after any whitespace character (\s)

I don't understand why \s selects characters after whitespace characters. From what I understand \s just selects whitespace characters. Is it because of the (^) at the start of the OR grouping? If so, why?

1 Answers

The regex symbol | means "or" essentially. So to break it down piece by piece:

(^|\s)\S

Piece 1: (^|\s) is "either ^ or \s" (but not both).

Choice 1: ^: Whatever is after should be at the beginning of the line (called "anchor"). Note: This is different from seeing ^ inside of brackets [].

Choice 2: \s: Any whitespace character

Piece 2: \S is any non-whitespace character.



So first it decides which part of Piece 1 it will choose.

Say it is Choice 1. Replace the whole regex with ^\S. This means "match any non-whitespace character (letters, numbers, etc.) at the beginning of the line.

Otherwise, it is Choice 2, which ends up as \s\S. This means "match any non-whitespace character after any whitespace character.

So, in summary: This regex will match any non-whitespace character at the beginning of the line or after a whitespace character.

Related