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!
Remove Duplicate Spaces Regex
Replace multiple consecutive spaces with a single space using regex pattern for text normalization.
Pattern Breakdown
regex
\s{2,}
Components
| Component | Description | Matches |
|---|---|---|
\s | Whitespace | Any whitespace character (space, tab, newline) |
{2,} | Quantifier | Two or more occurrences |
Character Classes
\s- Any whitespace character (space, tab, newline, etc.){2,}- Quantifier: two or more occurrences
Examples
Before Replacement:
Hello World→Hello WorldText with multiple spaces→Text with multiple spacesLine1\n\n\nLine2→Line1\nLine2(if using\s)Word1 Word2 Word3→Word1 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
- Spaces only:
{2,}- Only matches multiple spaces, not tabs/newlines - Whitespace:
\s{2,}- Matches any whitespace (spaces, tabs, newlines) - Trim after: Combine with trim to remove leading/trailing spaces
Limitations
- Whitespace type:
\smatches all whitespace, may needfor spaces only - No trim: Doesn't remove leading/trailing spaces automatically
- 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\sif 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!