Remove all whitespace from a string in JavaScript

Today, we’ll explain to you how to remove all whitespace from a string in JavaScript.

Replacing whitespace or blank space from a string is a common task. We can easily remove the empty space using JavaScript.

Different ways to remove whitespace from a string

  1. Regular expression
  2. Split() + Join()

1. Regular expression

The JavaScript string.replace() method supports regular expressions to find matches within the string.

Here is the example to replace all blank spaces in the string with an empty string. The g at the end performs the search and replace throughout the entire string.

If you want to remove all whitespace from a string and not just the literal space character, use \s instead. The /smatches all spaces character, tab character and newline breaks.

2. Split() + Join()

In another way, we can use the split() method with the join() method to remove the whitespace from a string in JavaScript.

The split() method splits the string using whitespace as a delimiter and returns them in the form of an array. The join() method joins the array of strings with empty strings.

That’s it for today.
Thank you for reading. Happy Coding..!! 🙂

If you found value in this article,
you can support us by buying me a coffee! ☕

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *