by Sai gowtham

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'

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
26,545 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
221,520 students enrolled
44 hours of video content
View Course
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
114,575 students enrolled
21 hours of video content
View Course