What does this .replace(/ {2,}/g, " ") regular expression do to a string?

Answered
nick asked this question 1 year, 6 months ago
nick on Mar 15, 2022 · Edited

I have come across the following regular expression being applied to strings:

.replace(/ {2,}/g, " ")

What does this do?

3 suggested answers
softwareguy411 on May 15, 2022

It takes a string, finds every instance of two or more spaces, and replaces it with a single space.

You can examine the regular expression here: https://regexr.com/6llmm.

0 replies
yaboy01 on May 15, 2022 · Edited

It finds each instance of a double space (or more) in a string and replaces it with a single space.

Here's an example:

let string = "     String    with      several    spaces.    ";

string = string.replace(/ {2,}/g, " ");

// string = " String with several spaces. "
0 replies
itsbambi on May 15, 2022

It finds any instances of two or more consecutive spaces and replaces it with one single space.

A breakdown:

  • {2,}: matches any instances of two or more consecutive spaces.
  • g: modifier that specifies a global match. So all matches are found (not just the first).
0 replies
Answered