Home > Web Front-end > JS Tutorial > How to Replace Multiple Spaces with a Single Space Using Regex?

How to Replace Multiple Spaces with a Single Space Using Regex?

Susan Sarandon
Release: 2024-11-08 01:35:02
Original
732 people have browsed it

How to Replace Multiple Spaces with a Single Space Using Regex?

Replacing Multiple Spaces with a Single Space Using Regex

In the realm of string manipulation, it often becomes necessary to tidy up excessive whitespace. A common issue is having strings with multiple consecutive spaces, which can clutter visual display or affect data consistency.

Suppose you have a string like:

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

How can we elegantly use regular expressions to ensure that spaces are limited to one space max? Our goal is to transform the string into:

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

Regex Solution

To achieve our goal, we can utilize the following regular expression:

string = string.replace(/\s\s+/g, ' ');
Copy after login

This regex searches for one or more consecutive spaces (s ) in the string and replaces them with a single space (' '). The 'g' flag ensures that this operation is performed globally, affecting all instances of multiple spaces.

Handling Special Cases

If you want to restrict the replacement to only spaces (excluding tabs, newlines, etc.), you can modify the regex as follows:

string = string.replace(/  +/g, ' ');
Copy after login

Here, the double space (ss) ensures that the regex matches only consecutive spaces and not other types of whitespace.

Implementation in JavaScript/jQuery

You can implement this regex-based solution in JavaScript or jQuery using the following code:

// Using jQuery
$("p").text(function(i, text) {
    return text.replace(/\s\s+/g, ' ');
});

// Using JavaScript
const string = "The dog      has a long   tail, and it     is RED!";
string.replace(/\s\s+/g, ' ');
Copy after login

The above is the detailed content of How to Replace Multiple Spaces with a Single Space Using 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