Search code examples
javascriptregexreplaceall

javascript - How to do replaceAll?


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.


Solution

  • 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);​