panzhuli
panzhuli

Reputation: 2940

URI Escaping n number of slashes in Javascript

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.

Upvotes: 1

Views: 790

Answers (1)

Elliot Bonneville
Elliot Bonneville

Reputation: 53351

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");

Upvotes: 2

Related Questions