Borislav Hadzhiev
Thu Oct 07 2021·2 min read
Photo by Vlad Bagacian
To remove all whitespace from a string, call the replace()
method, passing
it a regular expression that matches all whitespace characters and an empty
string as replacement. For example, str.replace(/\s/g, '')
returns a new
string with all whitespace removed.
const str = ' A B C D '; const noWhitespace = str.replace(/\s/g, ''); console.log(noWhitespace); // 👉️ 'ABCD'
The first parameter we passed to the String.replace method is a regular expression.
The \s
metacharacter matches spaces
, tabs
and newlines
.
We use the g
(global) flag to specify that we want to match all occurrences of
whitespace characters in the string, not just the first occurrence.
The second parameter the replace
function takes is the replacement. In our
case we want to replace all whitespace with an empty string (nothing).
String.replace
method does not change the original string, it returns a new string. Strings are immutable in JavaScript.