1

I'm trying to set up a replace for all "%2F" strings specifically for a search term. I have already run the search term through encudeURIComponent(search_term) and need to double escape ONLY the %2Fs.

If the search term is "ac/dc", I want the result to be: ac%252Fdc.

I can do this quickly like this:

search_term = encodeURIComponent(search_term);
search_term = search_term.replace("%2F", "%252F");

However, this doesn't work for ac//dc, which returns:

ac%252F%2Fdc

when what I want is:

ac%252F%252Fdc

I can solve this by running a replace like so...

search_term = search_term.replace("%2F%2F", "%252F%252F");

This isn't scalable. I'm wondering why doing the first replace isn't replacing both "%2F" strings.

Thank You.

panzhuli
  • 2,890
  • 6
  • 33
  • 46
  • possible duplicate of [How to replace all points in a string in JavaScript](http://stackoverflow.com/questions/2390789/how-to-replace-all-points-in-a-string-in-javascript) – Rob W May 06 '13 at 15:31
  • in the beginning you say you want the result to be "ac%252Fdc" and then you say "what I want is: ac%252F%252Fdc" - can you please clarify a bit? – Software Guy May 06 '13 at 15:40
  • Software Guy - please note that the search term changed between examples... – panzhuli May 06 '13 at 15:50

1 Answers1

2

You need to make the replace global, like this:

search_term = encodeURIComponent(search_term);
search_term = search_term.replace(new RegExp("%2F", 'g'), "%252F");

Hideous, I know, but it works.


Edit: As Rob W suggests, you're better off using a Regular expression literal to do this:

search_term = encodeURIComponent(search_term);
search_term = search_term.replace(/%2F/g, "%252F");
Elliot Bonneville
  • 51,872
  • 23
  • 96
  • 123
  • 3
    Use Regular expression literals instead of the RegExp constructor for constant regular expressions: `/%2F/g`. – Rob W May 06 '13 at 15:32
  • Thanks - I'm new to regular expressions - looks like some reading is in order!!!. I'll accept as soon as I can – panzhuli May 06 '13 at 15:37