How to remove whitespaces from strings in JavaScript?

November 9, 2020 - 3 min read

🌟 Jump to:

Remove whitespaces from both the left and right sides

To remove whitespaces from both sides of a string, you can use the trim() string method in JavaScript.

Consider this string with 4 spaces to its left and its right.

// string with 4 spaces
// in left and right sides
const str = "    Hai Jim    ";

Let's remove all the whitespaces using the trim() method like this,

// string with 4 spaces
// in left and right sides
const str = "    Hai Jim    ";

// remove whitespaces
const trimStr = str.trim();

console.log(trimStr); // "Hai Jim"

The method returns a new string with whitespaces removed from the left and right sides.

See this example live in JSBin.

Remove whitespaces only from the left side

To remove whitespaces only from the left side of a string, you can use the trimStart() string method in JavaScript.

Consider this string with 4 spaces to its left side.

// string with 4 spaces
// in left side
const str = "    Hai Jim";

Let's remove all the whitespaces to its left side using the trimStart() method like this,

// string with 4 spaces
// in left side
const str = "    Hai Jim";

// remove whitespaces from left
const trimStr = str.trimStart();

console.log(trimStr); // "Hai Jim"

The method returns a new string with whitespaces removed from the left side.

See this example live in JSBin

Remove whitespaces only from the right side

To remove whitespaces only from the right side of a string, you can use the trimEnd() string method in JavaScript.

Consider this string with 4 spaces to its right side.

// string with 4 spaces
// in right side
const str = "Hai Jim    ";

Let's remove all the whitespaces to its right side using the trimEnd() method like this,

// string with 4 spaces
// in right side
const str = "Hai Jim    ";

// remove whitespaces from right
const trimStr = str.trimEnd();

console.log(trimStr); // "Hai Jim"

The method returns a new string with whitespaces removed from the right side.

See this example live in JSBin.

Feel free to share if you found this useful 😃.