Search code snippets, questions, articles...

Remove all whitespaces from a string using javascript

If you have a String that contains multiple whitespaces in it and want to remove all the whitespace from that string then you can use the code examples used in this post. We will be removing them using regex and without using regex.
// define a string with multiple whitespace
const str = "     Programming Is    Fun    ";

// remove whitespace using regex
const result = str.replace(/s/g, '');

// print the result
console.log(result);
Best JSON Validator, JSON Tree Viewer, JSON Beautifier at same place.

Output

ProgrammingIsFun

Explanation

  1. Defined a Javascript string named str that contains multiple whitespaces.
  2. We are using the regex expression with the replace() function to remove whitespace from the string. 
  3. The replace() function will return the string without any whitespace.
  4. Printing the result in the console window.

Remove all whitespaces from string using replaceAll() function

We can also use the repalceAll() function of Javascript to remove all the white spaces from a string. The repalceAll() function takes two arguments - separator and joiner.

separator: The String that you want to replace.

joiner: The string that will be placed in the place of the separator.

Syntax

String.replaceAll(separator, joiner)

Code Example

const str = "     Programming Is    Fun    ";

const result = str.replaceAll(' ', '');

console.log(result);

Output

ProgrammingIsFun

Try it yourself

const str = "     Programming Is    Fun    ";

const result = str.split(' ').join('')

console.log(result);
If you do not want to use the regex in Javascript to remove all the whitespace from a String then you can use split() and join() functions.
In the above code example, we have defined a string with multiple whitespaces in it. Using the split() function we are splitting the string into an array and then joining the array using join() function with a blank string.
Was this helpful?
0 Comments