Search code examples
javascriptstringinternet-explorerreplacetapestry

Javascript replace % with $00 in Internet Explorer


As expected I need to encode a URI component before I call an API using it but when it hits our server somewhere along the line our backend framework (tapestry) converts spaces too early: Java URLEncoding / Decoding URL Spaces with dashes

I figured out that if I changed the URI %20 to $0020 it works. So the code below works in Chrome and Firefox and converts the % to a $00.

function furtherEncode(uriComp) {
  var nonSafe = encodeURIComponent(uriComp);
  return nonSafe.replace(/%/g, "$00");
}

In Internet Explorer 11 (and IE10) it doesn't do the replacement.

I have tried /\x25/g and /%/g as well as "$00" and '$00' but to no avail.

Any help would be greatly appreciated.


Solution

  • You need to have two dollar signs like here (tested in IE and Chrome):

    "%".replace(/%/g, "$$00") /// returns  "$00"
    

    See docs here: docs

    Relevant parts are defined under "Specifying a string as a parameter":

    $$ | Inserts a "$".
    $n | Where n or nn are decimal digits, inserts the nth parenthesized submatch string, provided the first argument was a RegExp object