464

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?

8
  • 8
    Are you trying to do URL-encoding of a string? If so, it's better to ask for help with that than just how to handle the spaces. Commented Sep 25, 2010 at 18:16
  • 2
    @Lasse, I suppose ultimately that is what I'm trying to do as the string that I want to format will eventually become part of a URL. However, I think the question still stands on its own merrit, as replacing all occurrences of a sub-string inside a string isn't immediately obvious.
    – DaveDev
    Commented Sep 25, 2010 at 20:13
  • 15
    Right, that was my suspicion too. The answer to that one is: use encodeURIComponent(). Don't try to hack it yourself with string replace; it's a lot trickier than you think. This will encode spaces to %20 rather than + though. %20 is just as valid (in fact more valid, as it works in path components, whereas + only means a space in query components), but if you want it to look marginally prettier you can always do a replace(/%20/g, '+') afterwards of course. You might be tempted to use escape() because it does use +, but it also gets all non-ASCII characters wrong—avoid.
    – bobince
    Commented Sep 26, 2010 at 0:39
  • 1
    I'll agree with that, the question has merit on its own :) I just wanted to know if that's where you were trying to end up, there might be better solutions for you. But yes, the question is good on its own, no doubt about that. I know enough javascript to scrape by, and that .replace didn't replace all the occurances was news to me. Commented Sep 26, 2010 at 6:55
  • 3
    Comparison of regex and split/join on tiny and longer strings. jsperf.com/replace-characters-in-string
    – iabw
    Commented Jul 20, 2012 at 18:48

9 Answers 9

621

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.

2
  • 1
    this has better readability than the split/join version imho
    – bobmoff
    Commented Dec 13, 2019 at 15:31
  • 1
    Oh, my ... I tried countless times of '/ /g' or something like that, there should be no quotation mark. Astonished me.
    – Zhang
    Commented Jun 18, 2021 at 13:28
602

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

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

EDIT 2024

Javascript now has String.replaceAll, supported by all browsers.

'a b c'.replaceAll('','+') would do the job.

19
  • 32
    This selected solution is slower on large replacement compared to the reg expression version. Test with the 3 solutions posted: jsbin.com/isadi3/2 Firefox has minimal timing difference, IE has a noticeable difference. So if speed matters and you have a large set of replacements, reg exp is the way to go. Commented Sep 30, 2010 at 4:27
  • 52
    use str = str.replace(/\s/g, "+"); Commented Jul 16, 2014 at 9:46
  • 4
    @JitendraPancholi that replaces all whitespace, not just the space character. The other regex answer here is fine. Commented Jul 16, 2014 at 10:23
  • 2
    @JitendraPancholi he wants to replace spaces, not "white spaces." In this context I assume by spaces he means only the space character, not just any old whitespace like /s would match. Particularly because he is doing this in JavaScript, and replacing the space character (but not other whitespace) with the + character is a standard way to encode URLs. This is probably why the regex solution that only replaces space characters has 10x the votes of the one that replaces all whitespace. Commented Jul 16, 2014 at 10:52
  • 1
    If your projects are using URLs with 30 spaces in them, you have bigger things to worry about than microptimizing string replacements. Commented Jul 16, 2014 at 11:09
134
var str = 'a b c';
var replaced = str.replace(/\s/g, '+');
1
  • 9
    Cleaner and faster than the chosen solution; works where / /g does not. Commented Dec 15, 2015 at 17:35
106

You can also do it like:

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

Have a look at this fiddle.

5
  • Could you please add explanation to why this is good solution to the problem. Commented Jul 16, 2014 at 10:47
  • 1
    Wasn't my downvote, I got a review task to check due to length of content. I assume someone more demanding didn't see explanation and downvoted without bothering to comment. Please put your comment into answer. Commented Jul 16, 2014 at 10:53
  • Ok, i have added fiddle in my answer. Commented Jul 16, 2014 at 10:55
  • 13
    Another possible reason for downvote is that this answer was already posted almost four years ago Commented Jul 25, 2014 at 13:25
  • 2
    @Jitendra Pancholi Thank you very much, you answer did help me, cuz I had some Japanese :) spaces, that I won't be able to replace by .split(' ').join('+'); Your answer did help me. Thanks man.
    – whitesiroi
    Commented May 15, 2015 at 10:48
34

Use global search in the string. g flag

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

source: replaceAll function

2
  • 1
    I have tested many regex above your answer, but your answer is the most right, because it also replaces multiple chainning white spaces.
    – O Connor
    Commented Jan 21, 2020 at 15:57
  • 5
    Does not work: Demo Input: "hello !!!", expected output: "hello++++!!!", actual output: "hello+!!!" Commented Jul 31, 2020 at 17:41
32

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.

16

You need to look for some replaceAll option

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

this is a regular expression way of doing a replaceAll.

function ReplaceAll(Source, stringToFind, stringToReplace) {
    var temp = Source;
    var index = temp.indexOf(stringToFind);

    while (index != -1) {
        temp = temp.replace(stringToFind, stringToReplace);
        index = temp.indexOf(stringToFind);
    }

    return temp;
}

String.prototype.ReplaceAll = function (stringToFind, stringToReplace) {
    var temp = this;
    var index = temp.indexOf(stringToFind);

    while (index != -1) {
        temp = temp.replace(stringToFind, stringToReplace);
        index = temp.indexOf(stringToFind);
    }

    return temp;

};
4
  • 4
    Wow. Er... there's a much simpler idiom for this: str.split(stringToFind).join(stringToReplace).
    – bobince
    Commented Sep 25, 2010 at 18:30
  • 1
    Wow is that inefficient. Commented Sep 25, 2010 at 19:02
  • @epascarello actually that performs way faster than a regex or above indfedelity :) Commented Sep 25, 2010 at 19:16
  • 3
    @Casper What browser are you seeing that in? jsbin.com/isadi3/edit Looking at the code it looks slow. Just for kicks I coded up a quick test and it is like 100X slower in browsers I tested it in. Commented Sep 26, 2010 at 3:27
7

NON BREAKING SPACE ISSUE

In some browsers

(MSIE "as usually" ;-))

replacing space in string ignores the non-breaking space (the 160 char code).

One should always replace like this:

myString.replace(/[ \u00A0]/, myReplaceString)

Very nice detailed explanation:

http://www.adamkoch.com/2009/07/25/white-space-and-character-160/

-3

Do this recursively:

public String replaceSpace(String s){
    if (s.length() < 2) {
        if(s.equals(" "))
            return "+";
        else
            return s;
    }
    if (s.charAt(0) == ' ')
        return "+" + replaceSpace(s.substring(1));
    else
        return s.substring(0, 1) + replaceSpace(s.substring(1));
}
1
  • 4
    There are already better solutions provided in the answers here. Commented Dec 5, 2017 at 17:53

Not the answer you're looking for? Browse other questions tagged or ask your own question.