Remove all whitespace from a string in JavaScript
This post will discuss how to remove all whitespace characters from a string in JavaScript.
The solution should remove all newline characters, tab characters, space characters, or any other whitespace character from the string.
1. Using Regular Expression
There is no JavaScript 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’s a working example that replaces all spaces in the string with an empty string (including leading, trailing, and multiple consecutive space characters). The g
switch in the regular expression performs the search and replace throughout the entire string.
1 2 3 4 5 6 |
const str = ' Hello World '; console.log(str.replace(/ /g,'')); /* Output: HelloWorld */ |
To remove all whitespace characters from the string, and not just the space character, use \s
instead. The \s
matches against all newline characters, tab characters, space characters, etc., This would translate to a simple code below:
1 2 3 4 5 6 |
const str = ' Hello World '; console.log(str.replace(/\s/g,'')); /* Output: HelloWorld */ |
2. Using Split()
with Join()
method
Another approach is to split the string using whitespace as a delimiter and then join it back together with an empty string. The following example demonstrates this by removing all contiguous space characters from the string.
1 2 3 4 5 6 |
const str = ' Hello World '; console.log(str.split(' ').join('')); /* Output: HelloWorld */ |
To remove all whitespace characters from the string, use \s
instead.
1 2 3 4 5 6 |
const str = ' Hello World '; console.log(str.split(/\s+/).join('')); /* Output: HelloWorld */ |
That’s all about removing all whitespace from a string in JavaScript.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)