views:

92

answers:

5

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 occurrance. How can I get it replace all occurrances?

+2  A: 

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.

Nick Craver
Are you sure that works? I think you need to use `/ /g`, not `' '/g`.
Mark Byers
@Mark - Saw that when I was pasting a demo, missed it first pass :)
Nick Craver
+1  A: 

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.

Mark Byers
A: 

You need to look for some replaceAll option

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

this is a regular expression way of doing a replaceAll .If you want a simple solution.

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;

    }

sushil bharwani
Wow. Er... there's a *much* simpler idiom for this: `str.split(stringToFind).join(stringToReplace)`.
bobince
Wow is that inefficient.
epascarello
@epascarello actually that performs way faster than a regex or above indfedelity :)
Caspar Kleijne
@Casper What browser are you seeing that in? http://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.
epascarello
A: 
var str = 'a b c';
var replaced = str.replace(/\s/g, '+');
epascarello
+1  A: 

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

var str = 'a b c';
var replaced = str.split(' ').join('+');
no
This selected solution is slower on large replacement compared to the reg expression version. Test with the 3 solutions posted: http://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.
epascarello