Trim all white space from string JavaScript

user3566643 picture user3566643 · Jul 4, 2014 · Viewed 39k times · Source

How can I remove all the white space from a given string.

Say:

var str = "  abc de fog   ";
str.trim(); 

Gives abc de fog AND NOT abcdefog, which I want.

How can I get all the white space removed using JavaScript?

Answer

Cute_Ninja picture Cute_Ninja · Jul 4, 2014

Use this:

str.replace(/\s+/g, '');

Instead of this:

str.trim()