How to replace white space in a string with ‘+’ in JavaScript
In this post we will give you information about How to replace white space in a string with ‘+’ in JavaScript. Hear we will give you detail about How to replace white space in a string with ‘+’ in JavaScriptAnd how to use it also give you demo for it if it is necessary.
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'Hope this code and post will helped you for implement How to replace white space in a string with ‘+’ in JavaScript. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs
