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
Release: 2024-11-06 14:56:02
Original
858 people have browsed it

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!"
Copy after login

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

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

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

/[\s\s+]/g
Copy after login

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, ' ');
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template