Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to trim whitespace from a string

Short answer

The trim() method strips spaces, tabs and line breaks from both ends:

console.log('[' + '  text  '.trim() + ']');

Output:

[text]

One side only

trimStart() strips the start of the string, trimEnd() the end:

console.log('[' + '  text  '.trimStart() + ']');
console.log('[' + '  text  '.trimEnd() + ']');

Output:

[text  ]
[  text]

Extra spaces inside the string

trim() leaves the middle of the string alone. A regular expression collapses repeated spaces into one:

console.log('one   two    three'.replace(/\s+/g, ' '));

Output:

one two three

Common mistake

trim() returns a new string, it does not change the variable. Save the result:

let name = '  Anna  ';
name.trim();
console.log('[' + name + ']');
 
name = name.trim();
console.log('[' + name + ']');

Output:

[  Anna  ]
[Anna]

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.