🔍Regex Recipes
Remove Duplicate Spaces
Find and replace multiple consecutive spaces with a single space.
Pattern
{2,}Explanation
Matches two or more consecutive spaces. Use with find-replace to normalize whitespace.
Examples
Double spaces
Input
Hello world
Output
Replace with: Hello world
Multiple spaces
Input
Too many spaces
Output
Replace with: Too many spaces
Already normalized
Input
Normal spacing
Output
No change
Code Examples
JavaScript
// Remove duplicate spaces
const text = 'Too many spaces';
const normalized = text.replace(/ {2,}/g, ' ');
// Result: 'Too many spaces'
// Also trim and collapse all whitespace
const fullyNormalized = text
.replace(/\s+/g, ' ') // All whitespace to single space
.trim(); // Remove leading/trailingTry it Now
💡 Tips
- Use \s+ to match all whitespace types
- Combine with trim() for complete normalization
- Useful for cleaning pasted text
- Test with actual data to avoid over-normalization
⚠️ Common Pitfalls
- Does not handle other whitespace (tabs, newlines)
- May want to preserve intentional spacing (code, tables)
- Consider trimming leading/trailing spaces too
- Different from \s+ which matches all whitespace