Home  >  Article  >  Web Front-end  >  How to Compress Multiple Spaces into a Single Space with Regex?

How to Compress Multiple Spaces into a Single Space with Regex?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-12 14:43:02361browse

How to Compress Multiple Spaces into a Single Space with Regex?

Regex Solution for Compressing Multiple Spaces into a Single Space

Replacing multiple spaces with a single space is a common task in text processing. Here's a jQuery or JavaScript solution using a regular expression to achieve this goal:

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

This regex uses a global search (g) to identify all occurrences of two or more consecutive spaces (ss ) and replaces them with a single space.

If you want to specify only spaces and exclude other whitespace characters (e.g., tabs, newlines), use this modified regex:

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

Here's an example of how the modified regex works:

const input = "The dog      has a long   tail, and it     is RED!";
const output = input.replace(/  +/g, ' ');
console.log(output); // Outputs: "The dog has a long tail, and it is RED!"

By applying this regex, you can effectively compress any consecutive spaces in a string into just one space, making the text more readable and consistent.

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