Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace all spaces in a string with '+' [duplicate]

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?

like image 842
DaveDev Avatar asked Sep 25 '10 18:09

DaveDev


People also ask

How do you replace all spaces in a string?

Use the String. replace() method to replace all spaces in a string, e.g. str. replace(/ /g, '+'); . The replace() method will return a new string with all spaces replaced by the provided replacement.

How do you replace multiple spaces?

The metacharacter “\s” matches spaces and + indicates the occurrence of the spaces one or more times, therefore, the regular expression \S+ matches all the space characters (single or multiple). Therefore, to replace multiple spaces with a single space.

How do I remove multiple spaces in a string?

Using sting split() and join() You can also use the string split() and join() functions to remove multiple spaces from a string. We get the same result as above. Note that the string split() function splits the string at whitespace characters by default.


1 Answers

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

var str = 'a b c'; var replaced = str.split(' ').join('+'); 
like image 172
Dagg Nabbit Avatar answered Sep 25 '22 17:09

Dagg Nabbit