Replace all spaces in a string with ‘+’ [duplicate]

Replace all spaces in a string with ‘+’ [duplicate]

This question already has an answer here:

How to replace all occurrences of a string in JavaScript

55 answers

I have a string that contains multiple spaces. I want to replace these with a plus symbol. I thought I could use
var str = ‘a b c’;
var replaced = str.replace(‘ ‘, ‘+’);

but it only replaces the first occurrence. How can I get it replace all occurrences?

Solutions/Answers:

Solution 1:

Here’s an alternative that doesn’t require regex:

var str = 'a b c';
var replaced = str.split(' ').join('+');

Solution 2:

You need the /g (global) option, like this:

var replaced = str.replace(/ /g, '+');

You can give it a try here. Unlike most other languages, JavaScript, by default, only replaces the first occurrence.

Solution 3:

var str = 'a b c';
var replaced = str.replace(/\s/g, '+');

Solution 4:

You can also do it like

str = str.replace(/\s/g, "+");

Have a look to the fiddle

Solution 5:

Use global search in the string. g flag

str.replace(/\s+/g, '+');

source: replaceAll function

Solution 6:

Use a regular expression with the g modifier:

var replaced = str.replace(/ /g, '+');

From Using Regular Expressions with JavaScript and ActionScript:

/g enables “global” matching. When using the replace() method, specify this modifier to replace all matches, rather than only the first one.