Code Premix

Remove whitespace from a string using JavaScript

📅April 29, 2022

Today, we’ll explain to you how to remove 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.

const str = '  Welcome to CodePremix ';
console.log(str.replace(/ /g,''));
// Output: WelcometoCodePremix

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.

const str = '  Welcome to CodePremix ';
console.log(str.replace(/\s/g,''));
// Output: WelcometoCodePremix

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.

const str = '  Welcome to CodePremix ';
console.log(str.split(' ').join(''));
// Output: WelcometoCodePremix

That’s all I’ve got for today.
Thank you for reading. Happy Coding..!!