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'

Css Tutorials & Demos

How rotate an image continuously in CSS

In this demo, we are going to learn about how to rotate an image continuously using the css animations.

How to create a Instagram login Page

In this demo, i will show you how to create a instagram login page using html and css.

How to create a pulse animation in CSS

In this demo, i will show you how to create a pulse animation using css.

Creating a snowfall animation using css and JavaScript

In this demo, i will show you how to create a snow fall animation using css and JavaScript.

Top Udemy Courses

JavaScript - The Complete Guide 2022 (Beginner + Advanced)
JavaScript - The Complete Guide 2022 (Beginner + Advanced)
116,648 students enrolled
52 hours of video content
$14.99 FROM UDEMY
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
631,582 students enrolled
49 hours of video content
$24.99 FROM UDEMY
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
203,937 students enrolled
31.5 hours of video content
$14.99 FROM UDEMY