JavaScript Remove Whitespace From String: 3 Effective Methods

Explore different methods to remove whitespace from string in JavaScript.

In this article, we will show you how to use the trim(), replace(), and split() methods effectively.

You will learn and understand their different behaviors and see examples of each method in action.

Whether you’re looking for a way to remove whitespace from the beginning, end, or anywhere within a string, this article has covered it.

Different methods to remove whitespace in JavaScript?

The following are the different methods you may use to remove whitespace in JavaScript.

Please note that these methods have different behaviors.

Using the trim() method

The trim() method removes whitespace from both ends of a string. This method removes spaces, tabs, and line breaks from both ends of a string.

Here’s an example:

const samplestring = "  Welcome to Itsourcecode!  ";
const trimmedString = samplestring.trim(); ✅


📌Note: The trim() method only removes whitespace from the beginning and end of a string.


Welcome to Itsourcecode!

Using the replace() method with a regular expression

The replace() method can be used with a regular expression to replace all whitespace characters from string in JavaScript.

Here is an example of how to remove whitespace from string JavaScript:

let samplestring =  "  Welcome to Itsourcecode!  ";
str = samplestring.replace(/\s/g, '');



Aside from that, the replace() method can be used with a regular expression to replace leading and trailing whitespace characters.

Here’s example:

let samplestring =  " Hello, Welcome to Itsourcecode!  ";
str = samplestring.replace(/^\s+|\s+$/g, ''); 


Hello, Welcome to Itsourcecode!

Using the split() and join() methods

The split() method splits a string into an array of substrings, and the join() method joins the elements of an array into a string.

Here is an example:

let samplestring =  " Hi, Welcome to!  ";
str = samplestring.split(' ').join(''); 



In addition to that, the split() and join() methods can also be used to remove leading and trailing spaces.

Here’s an example:

let samplestring =  " Hi, Welcome to Itsourcecode!  ";
str = samplestring.split(' ').filter(Boolean).join(' '); 


Hi, Welcome to Itsourcecode!


In conclusion, we can remove whitespace from strings in JavaScript using various methods such as trim()replace(), and split() & join().

Each method has its use cases and behaviors, so you can choose the one that best fits your needs.

We are hoping that this article provides you with enough information that helps you understand the JavaScript removes whitespace.

If you want to dive into more JavaScript topics, check out the following articles:

Thank you for reading Itsourcecoders 😊.

Leave a Comment