1

Hi I have a problem here. I am trying to replace all instances of + character in a string using javascript. What happens is that only the first instance is being changed.

Here is my code:

var keyword = "Hello+Word%+";
keyword = keyword.replace("+", encodeURIComponent("+"));
alert(keyword);

The output is Hello%2BWord%+ when it should be Hello%2BWord%%2B because there are 2 instances of +.

You can check this on : http://jsfiddle.net/Wy48Z/

Please help. Thanks in advance.

NinjaBoy
  • 3,715
  • 18
  • 54
  • 69

3 Answers3

2

You need the global flag.

Fixed for you at http://jsfiddle.net/rtoal/Wy48Z/1/

var keyword = "Hello+Word%+";
keyword = keyword.replace(/\+/g, encodeURIComponent("+"));
alert(keyword);​
Ray Toal
  • 86,166
  • 18
  • 182
  • 232
  • So that what g is about. I always see that on lots of examples but I thought its just a random character. – NinjaBoy Jul 13 '12 at 01:59
  • Oh, sorry, should have added to the answer. After the `/.../` you can place a modifier character such as s, g, or i. g means do the replacement everywhere, i means case-insensitive. You can look them up [here](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/RegExp/). – Ray Toal Jul 13 '12 at 02:03
1

The javascript regex, which is done by putting the expresison inbetween two forward slashes like: /<expression/

If you want to replace all, simply append a g after the last one like:

/<expression/g

In your case, it would be /\+/g

OnResolve
  • 4,016
  • 3
  • 28
  • 50
1

The cross-browser approach is to use a regexp with the g (global) flag, which means "process all matches of the pattern, not just the first":

keyword = keyword.replace(/\+/g, encodeURIComponent("+"));

Notice I prefix the plus sign with a backslash because it would otherwise have the special meaning of "match one or more of the preceding thing".

PleaseStand
  • 31,641
  • 6
  • 68
  • 95