How to replace white space in a string with '+' in JavaScript
In this tutorial, we are going to learn about how to use regex to replace all white space in a given string with + sign using JavaScript.
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 + sign.
In JavaScript, we can do that by using a String.replace() method.
Example:
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 + sign.
The regex /\s/g helps us to remove the all-white space in the string.
Second way
There is also an alternative way by using split() and join() methods without using regex.
const str = 'a b c';
console.log(str.split(' ').join('+')); // 'a+b+c'

