Remove the whitespaces from a string using replace() in JavaScript?

In JavaScript, the replace()

Basic Syntax

string.replace(regex, replacement)

Removing Leading and Trailing Whitespaces

Use the regex /^\s+|\s+$/g to remove whitespaces from the beginning and end of a string:

function removeSpacesAtTheBeginningAndTheEnd(name) {
    return name.toString().replace(/^\s+|\s+$/g, '');
}

var fullName = " John Smith ";
var valueAfterRemovingSpace = removeSpacesAtTheBeginningAndTheEnd(fullName);
console.log("Original: '" + fullName + "'");
console.log("Trimmed: '" + valueAfterRemovingSpace + "'");
Original: ' John Smith '
Trimmed: 'John Smith'

Different Types of Whitespace Removal

Remove All Whitespaces

var text = " Hello World ";
var noSpaces = text.replace(/\s/g, '');
console.log("'" + text + "' ? '" + noSpaces + "'");
' Hello World ' ? 'HelloWorld'

Remove Only Leading Whitespaces

var text = "   Hello World   ";
var noLeadingSpaces = text.replace(/^\s+/, '');
console.log("'" + text + "' ? '" + noLeadingSpaces + "'");
'   Hello World   ' ? 'Hello World   '

Remove Only Trailing Whitespaces

var text = "   Hello World   ";
var noTrailingSpaces = text.replace(/\s+$/, '');
console.log("'" + text + "' ? '" + noTrailingSpaces + "'");
'   Hello World   ' ? '   Hello World'

Regex Pattern Explanation

Pattern Description Result
/^\s+|\s+$/g Leading OR trailing spaces Trims both ends
/\s/g All whitespace characters Removes all spaces
/^\s+/ Only leading spaces Removes from start
/\s+$/ Only trailing spaces Removes from end

Alternative: Using trim()

For removing leading and trailing whitespaces, JavaScript's built-in trim() method is more concise:

var fullName = " John Smith ";
console.log("Using replace(): '" + fullName.replace(/^\s+|\s+$/g, '') + "'");
console.log("Using trim(): '" + fullName.trim() + "'");
Using replace(): 'John Smith'
Using trim(): 'John Smith'

Conclusion

The replace() method with regex provides flexible whitespace removal options. For simple trimming, use the built-in trim() method, but use replace() when you need more specific whitespace control.

Updated on: 2026-03-15T23:18:59+05:30

232 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements