How do you remove whitespace from a string in Javascript?

There are several ways to remove whitespace from a string in JavaScript.

Here are some commonly used methods:

1. Using replace() method with a regular expression:

The replace() method in JavaScript can be used with a regular expression to replace all occurrences of a pattern with a replacement value.

You can use the regular expression \s to represent whitespace characters (spaces, tabs, and newlines), and the g flag to indicate a global search, meaning all occurrences of the pattern will be replaced.

Here is an example:

const str = " remove whitespace from this string ";
const result = str.replace(/\s/g, "");
console.log(result); // "removewhitespacefromthisstring"

2. Using split() and join() methods:

The split() method can be used to split a string into an array of substrings based on a specified delimiter. In this case, you can use the whitespace character as the delimiter. Then, you can use the join() method to join the substrings without any separator, effectively removing the whitespace.

Here is an example:

const str = " remove whitespace from this string ";
const result = str.split(" ").join("");
console.log(result); // "removewhitespacefromthisstring"

3. Using trim() method:

The trim() method is used to remove leading and trailing whitespace characters from a string. It does not remove whitespace characters within the string.

Here’s an example:

const str = " remove whitespace from this string ";
const result = str.trim();
console.log(result); // "remove whitespace from this string"

If you want to remove all whitespace characters from the entire string, you can combine trim() with replace() method using a regular expression:

const str = " remove whitespace from this string ";
const result = str.replace(/\s+/g, "");
console.log(result); // "removewhitespacefromthisstring"

4. Using replaceAll() method (ES2021):

The replaceAll() method is a newer addition to Javascript introduced in ES2021, and it allows you to replace all occurrences of a pattern in a string with a replacement value.

You can use it to replace all whitespace characters with an empty string, like this:

const str = " remove whitespace from this string ";
const result = str.replaceAll(/\s/g, "");
console.log(result); // "removewhitespacefromthisstring"

Note: Keep in mind that the replaceAll() method is not supported in older JavaScript versions, so make sure to check for compatibility before using it in your code.

Thank you for reading, and let’s have conversation with each other

Thank you for reading my article. Let’s have conversation on Twitter and LinkedIn by connecting.

Read more: