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?
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.
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.
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.
Here's an alternative that doesn't require regex:
var str = 'a b c'; var replaced = str.split(' ').join('+');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With