replace() method on the string, passing a regular expression that matches any whitespace character, and an empty string as a replacement. For example,
str.replace(/\s/g, '') returns a new string with all whitespace removed from
const str = '1 2 3'; const whitespaceRemoved = str.replace(/\s/g, ''); console.log(whitespaceRemoved); // 123
\s regex metacharacter matches whitespace characters, such as spaces, tabs, and newlines.
We use the
g regex flag to specify that all whitespace characters in the string should be matched. Without this flag, only the first whitespace will be matched and replaced:
const str = '1 2 3'; // No 'g' flag in regex const whitespaceRemoved = str.replace(/\s/, ''); // Only first whitespace removed console.log(whitespaceRemoved); // 12 3
replace() method returns a new string with all the matches replaced with the second argument passed to it. We pass an empty string (
'') as the second argument to replace all the whitespace with nothing, which effectively removes them.
const str = '1 2 3'; const whitespaceRemoved = str.replace(/\s/g, ''); console.log(whitespaceRemoved); // 123 // Not modified console.log(str); // 1 2 3
Ayibatari Ibaba is a software developer with years of experience building websites and apps. He has written extensively on a wide range of programming topics and has created dozens of apps and open-source libraries.