Home >Web Front-end >JS Tutorial >How to Eliminate Multiple Spaces in a String with Regex?

How to Eliminate Multiple Spaces in a String with Regex?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-06 14:56:02879browse

How to Eliminate Multiple Spaces in a String with Regex?

Eliminating Multiple Spaces with Regex

To streamline strings with excessive whitespace, we can leverage regular expressions in jQuery or JavaScript. Let's consider the example:

"The dog      has a long   tail, and it     is RED!"

Our goal is to condense multiple spaces into a single space, resulting in:

"The dog has a long tail, and it is RED!"

To achieve this transformation, we can utilize the following regular expression:

/[\s\s+]/g

Here's how it works:

  • [ss ]: This part matches two or more consecutive whitespace characters (s represents a single whitespace character).
  • /g: This global modifier ensures that all instances of multiple spaces in the string are replaced.

Using the replace method, we can execute the replacement:

string = string.replace(/[\s\s+]/g, ' ');

By doing so, we efficiently replace all occurrences of multiple spaces with a single space, achieving our desired string format.

The above is the detailed content of How to Eliminate Multiple Spaces in a String with Regex?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn