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

Answered
nick asked this question 2 months ago
nick on Mar 15 · Edited

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

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

What does this do?

3 suggested answers
softwareguy411 9 days ago

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 9 days ago · 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 9 days ago

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