What does this .replace(/\s+/g, " ") regular expression do?

Answered
looper003 asked this question 2 months ago
looper003 on Mar 15

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

.replace(/\s+/g, " ")

What does this do?

3 suggested answers
moon_man41 9 days ago

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 = "     A string    with      many    spaces.    ";

string = string.replace(/\s+/g, " ");

// string = " A string with many spaces. "

Notice that any double, triple, etc. space is converted into a single space.

0 replies
softwareguy411 9 days ago

It replaces all double or more spaces with a single space.

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

0 replies
itsbambi 9 days ago

It finds any whitespace with two or more spaces and replaces it with a single space.

A breakdown:

  • \s: matches any whitespace in the string.
  • +: quantifier that matches any whitespace greater than one space
  • g: modifier that specifies a global match. So all matches are found (not just the first).
0 replies
Answered