How To Remove all Whitespace from a String in JavaScript

Remove all Whitespace from a String in JavaScript

This article will show you how to remove all whitespace from a string in JavaScript. Let’s follow the methods below.

Remove all whitespaces from a string in JavaScript

Remove all spaces in JavaScript strings with split() and join()

In the previous lessons, we learned that the split() method helps to split a string into small strings with a separator character. And the join() method helps to join the elements in an array into a string using a separator character.

The idea here is we will use split() to split the original string with spaces and get the result as an array. Then, use the join() method with the argument as a space character '' to join the elements in the array without using the separator character, thereby removing all spaces in the original string.

Code sample

let myString = "  Learn   Share    IT   ";
let myArr = myString.split(" ").join("");
 
console.log(myArr);

Output

LearnShareIT

Use replace() method and RegEx regular expression

Another simple way to help us remove all spaces in a JavaScript string is to use the replace() method with an argument of a RegEx regular expression in the format of a glocal flag.

We use the replace() method in the usual way to replace the first occurrence of a character in a JavaScript string.

For example, we replace the string IT in the string by the string Maths with replace() as follows.

Code sample

let myString = "  Learn   Share      IT   ";
let newString = myString.replace('IT', 'Maths');
 
console.log(newString);

Output

  Learn   Share      Maths

Using this function, we can use replace() to replace the spaces in the string with empty characters and thereby complete the removal of all spaces in the original string.

Again, since the regular replace() method only replaces the first character found, we need to use it with a regular expression as the glocal flag to be able to do this. Replace all characters in the string.

In this example, we use RegEx to represent spaces as a glocal flag of /\s/g and remove all spaces in the string as follows:

Code sample

let myString = "  Learn   Share      IT   ";
let newString = myString.replace(/\s/g, '');
 
console.log(newString);

Output

LearnShareIT

Summary

Above, I showed you how to remove all whitespace from a string in JavaScript. I hope they are helpful to you. To better understand the lesson’s content, practice rewriting today’s examples. And let’s learn more about Javascript in the next lessons here. Have a great day!

Maybe you are interested:

Leave a Reply

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