Back to Home

Remove Duplicate Spaces Regex

CronOS Team
regextext-processingreplacementtutorialnormalization

Need to generate a regex pattern?

Use CronOS to generate any regex pattern you wish with natural language. Simply describe what you need, and we'll create the perfect regex pattern for you. It's completely free!

Generate Regex Pattern

Remove Duplicate Spaces Regex

Replace multiple consecutive spaces with a single space using regex pattern for text normalization.

Pattern Breakdown

regex
\s{2,}

Components

ComponentDescriptionMatches
\sWhitespaceAny whitespace character (space, tab, newline)
{2,}QuantifierTwo or more occurrences

Character Classes

  • \s - Any whitespace character (space, tab, newline, etc.)
  • {2,} - Quantifier: two or more occurrences

Examples

Before Replacement:

  • Hello WorldHello World
  • Text with multiple spacesText with multiple spaces
  • Line1\n\n\nLine2Line1\nLine2 (if using \s)
  • Word1 Word2 Word3Word1 Word2 Word3

After Replacement:

  • All multiple spaces become single spaces

Implementation

JavaScript

javascript
const text = 'Hello    World    with    spaces';
const normalized = text.replace(/\s{2,}/g, ' ');
// Result: "Hello World with spaces"

// For spaces only (not tabs/newlines)
const spaceOnly = text.replace(/ {2,}/g, ' ');

Python

python
import re
text = 'Hello    World    with    spaces'
normalized = re.sub(r'\s{2,}', ' ', text)
# Result: "Hello World with spaces"

# For spaces only
space_only = re.sub(r' {2,}', ' ', text)

Go

go
import "regexp"
text := "Hello    World    with    spaces"
spaceRegex := regexp.MustCompile(`\s{2,}`)
normalized := spaceRegex.ReplaceAllString(text, " ")
// Result: "Hello World with spaces"

// For spaces only
spaceOnlyRegex := regexp.MustCompile(` {2,}`)
normalized = spaceOnlyRegex.ReplaceAllString(text, " ")

Variations

  1. Spaces only: {2,} - Only matches multiple spaces, not tabs/newlines
  2. Whitespace: \s{2,} - Matches any whitespace (spaces, tabs, newlines)
  3. Trim after: Combine with trim to remove leading/trailing spaces

Limitations

  1. Whitespace type: \s matches all whitespace, may need for spaces only
  2. No trim: Doesn't remove leading/trailing spaces automatically
  3. Replacement pattern: This is a replacement pattern, not validation

When to Use

  • Text normalization
  • Cleaning user input
  • Preparing text for processing
  • Removing formatting artifacts
  • Text sanitization

For production, consider:

  • Using instead of \s if you only want spaces
  • Trimming result: .trim() or .strip()
  • Handling other whitespace characters separately if needed
  • Preserving intentional formatting in some cases

Need to generate a regex pattern?

Use CronOS to generate any regex pattern you wish with natural language. Simply describe what you need, and we'll create the perfect regex pattern for you. It's completely free!

Generate Regex Pattern