In this tutorial, we are going to learn about how to use regex to replace all white space in a given string with
Consider we have a string like this.
const str = 'a b c';
Now we need to replace all white space in the above string with plus
const str = 'a b c'; console.log(str.replace(/\s/g, '+')); // 'a+b+c'
In the above code, we have passed two arguments to the
replace() method first one is regex
/\s/g and the second one is replacement value
+, so that the
replace() method will replace all-white spaces with a
/\s/g helps us to remove the all-white space in the string.
There is also an alternative way by using
join() methods without using regex.
const str = 'a b c'; console.log(str.split(' ').join('+')); // 'a+b+c'