How to transform two or more spaces in a string in only one space? JavaScript

In JavaScript, you can transform multiple consecutive spaces in a string into a single space using regular expressions with the replace() method. This is useful for cleaning up text input or formatting strings consistently.

The Regular Expression Approach

The most effective method uses the regular expression /\s{2,}/g where:

  • \s matches any whitespace character (spaces, tabs, newlines)
  • {2,} matches two or more consecutive occurrences
  • g is the global flag to replace all instances

Method 1: Using replace() with Regular Expression

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Remove Extra Spaces</title>
</head>
<body>
    <input type="text" id="textInput" value="This   has    multiple     spaces" placeholder="Enter text with extra spaces">
    <button onclick="removeExtraSpaces()">Clean Spaces</button>
    <p id="result"></p>

    <script>
        function removeExtraSpaces() {
            const input = document.getElementById('textInput');
            const result = document.getElementById('result');
            
            const originalText = input.value;
            const cleanedText = originalText.replace(/\s{2,}/g, ' ');
            
            input.value = cleanedText;
            result.innerHTML = `Original: "${originalText}"<br>Cleaned: "${cleanedText}"`;
        }
    </script>
</body>
</html>

Method 2: Console-based Example

function cleanSpaces(text) {
    return text.replace(/\s{2,}/g, ' ');
}

// Test with different examples
const examples = [
    "Hello    world",
    "Multiple     spaces    here",
    "Normal text",
    "Tabs\t\tand    spaces"
];

examples.forEach(text => {
    const cleaned = cleanSpaces(text);
    console.log(`Original: "${text}"`);
    console.log(`Cleaned:  "${cleaned}"`);
    console.log('---');
});
Original: "Hello    world"
Cleaned:  "Hello world"
---
Original: "Multiple     spaces    here"
Cleaned:  "Multiple spaces here"
---
Original: "Normal text"
Cleaned:  "Normal text"
---
Original: "Tabs		and    spaces"
Cleaned:  "Tabs and spaces"
---

Alternative Methods

const text = "Text   with    extra     spaces";

// Method 1: Using split and join
const method1 = text.split(/\s+/).join(' ');
console.log("Split/Join:", method1);

// Method 2: Using multiple replace calls
const method2 = text.replace(/\s+/g, ' ');
console.log("Replace \s+:", method2);

// Method 3: Trim edges and clean middle
const method3 = text.trim().replace(/\s{2,}/g, ' ');
console.log("Trim + Clean:", method3);
Split/Join: Text with extra spaces
Replace \s+: Text with extra spaces
Trim + Clean: Text with extra spaces

Comparison of Methods

Method Handles All Whitespace? Performance Readability
/\s{2,}/g Yes Good Clear intent
split().join() Yes Slower Very clear
/\s+/g Yes Best Simple

Practical Use Case

<!DOCTYPE html>
<html>
<head>
    <title>Text Cleaner</title>
</head>
<body>
    <textarea id="textArea" rows="4" cols="50" placeholder="Paste text with extra spaces here...">This    text   has     irregular    spacing</textarea>
    <br><br>
    <button onclick="cleanText()">Clean Text</button>
    <button onclick="resetText()">Reset</button>
    
    <script>
        const originalText = "This    text   has     irregular    spacing";
        
        function cleanText() {
            const textarea = document.getElementById('textArea');
            textarea.value = textarea.value.replace(/\s{2,}/g, ' ').trim();
        }
        
        function resetText() {
            document.getElementById('textArea').value = originalText;
        }
    </script>
</body>
</html>

Conclusion

Use text.replace(/\s{2,}/g, ' ') to replace multiple consecutive spaces with single spaces. For more comprehensive cleanup, use /\s+/g to handle all types of whitespace characters efficiently.

Updated on: 2026-03-15T23:19:00+05:30

348 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements