Normalise whitespace in a string using regex

Nikhil Vijayan
1 min readOct 19, 2021

To normalise a string with extra spaces, for eg:

The  quick brown fox jumps over   the lazy  dog

To take out extra spaces, here’s the regex you can use:

const myString = 'The  quick brown fox jumps over   the lazy  dog'
normalisedString = myString.replace(/(\s)\s+/g, '$1')

Parenthesis in REGEX are used to create capturing groups.

Capturing groups do 2 things:

  • Allows to get a part of the match as a separate item in the result array.
  • If we put a quantifier after the parentheses, it applies to the parentheses as a whole

\s denotes a space, and (\s) denotes a capture group that captures a space character. (\s)\s+ will match 2 consecutive spaces and + denotes Match 1 or more of the preceding tokens , so it will match 2 or more space characters. The /g flag looks for the pattern globally.

The '$1' denotes the first element captured, and is used to replace what the matcher argument matched, which was ‘2 or more space characters’.