How to remove all whitespaces from a string

Mo Ibra

Mo Ibra

Dec 23, 2022

In this article we will learn how remove all whitespaces from a string.

It is very common remove all whitespaces from a string in JavaScript.


Problem

Now we have a problem, which is that we want to delete all whitespaces from a string.

Imagine we have a string like this:

"Hello In My World";

And we want to remove whitespaces to became like this:

"HelloInMyWorld"

How to solve this problem?

Well, the solution to this problem is not difficult, because through the replace() method and regular expression, we can do that.


Remove all whitespaces from a string using replace

As we said before we can use replace method with regular expression to solve this problem.

Example

// String
const string = "Hello In My World";

// Remove whitespaces
const result = string.replace(/\s/g, '');

// Result:
console.log(result);

Output

HelloInMyWorld

Remove all whitespaces from a string using replaceAll

We can use replaceAll() to solve this problem as well.

Example

// String
const string = "Hello In My World";

// Remove whitespaces
const result = string.replaceAll(/\s/g, '');

// Result:
console.log(result);

Output

HelloInMyWorld

Thank you for reading

Thank you for reading my blog. 🚀

Suggestions For More Articles: