Home > Web Front-end > JS Tutorial > body text

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

Patricia Arquette
Release: 2024-11-12 14:43:02
Original
403 people have browsed it

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

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

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

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!

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