Remove all whitespace from a string in JavaScript

In this post we are going to share how to remove all whitespace characters from a string in JavaScript. In JavaScript we have a native method replaceAll(), which replaces all instances of a character with a replacement. The general strategy for replacing a pattern in the given string is using the replace() method, which can accept a RegExp object.

Here bellow the best solution’s examples added for remove all newline characters, tab characters, space characters, or any other whitespace character from the string.

Example 1:

const str = ' h   e   l    l  o ';

const noWhitespace = str.replace(/\s/g, '');
console.log(noWhitespace); // 'hello'

Example 2:

const str = ' h   e   l    l  o ';

const noWhitespace = str.replaceAll(/\s/g, '');

console.log(noWhitespace); // 'hello'

Example 3:

const str = ' h   e   l    l  o ';

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

console.log(noWhitespace); // 'hello'

Example 4:

const str = ' h   e   l    l  o ';

const noWhitespace = str.split(/\s+/).join('');

console.log(noWhitespace); // 'hello'