Back to Home
Strings

How to Remove Whitespace from Strings

Use .trim() to remove leading and trailing whitespace

Quick Answer (2024 ES6+ Way)

javascript
const text = '  Hello World  ';
const trimmed = text.trim();
console.log(trimmed); // "Hello World"

Live Example

javascript
const userInput = '  [email protected]  ';

// Clean user input
const email = userInput.trim().toLowerCase();
console.log(email);

// Remove all whitespace
const phone = '  (555) 123-4567  ';
const cleaned = phone.replace(/\s/g, '');
console.log(cleaned);

Common Variations

Trim Start/End Only
javascript
const text = '  hello  ';
text.trimStart(); // "hello  "
text.trimEnd();   // "  hello"
Remove Extra Spaces
javascript
const text = 'too    many    spaces';
const normalized = text.replace(/\s+/g, ' ');
// "too many spaces"

❌ Don't Do This (Outdated Way)

Avoid manual string manipulation

javascript
// DON'T DO THIS
var trimmed = text.replace(/^\s+|\s+$/g, '');

Browser Support

Works in all modern browsers (ES5+)

#strings#trim#whitespace