Using local variables with JavaScript’s replace() function
Recently, I’ve been working on some client-side code for a web application that needed to encode some data prior to invoking an AJAX request, and then needed to decode the response data upon receiving a successful response; however, I discovered a nuance in JavaScript’s replace() function that required a little bit of extra work to get it operator with the degree of flexibility that I wanted.
Because ampersands are usually used to delimit query string parameters, the server wasn’t handling the submitted data correctly. To mitigate this issue, the ampersand character needed to be encoded. We stored the encoded representation of the ampersand in a local variable [creatively] called _ampersand.Next, we wrote a function that takes in the data to be sent across the wire, encodes the characters, and does some additional processing, before returning the encoded data:
function encodedData(strInput) {
return strInput.replace(/&/g, _ampersand);
}
It worked fine; however, the replace() function proved to require a little additional work for it to decode the data correctly. Since we needed to do a global replacement of the ampersand token, we were using the g operator, but inserting a variable into the replace() function does not work. Actions speak louder than works, so here’s what I mean:
// this does not work…
function restoreAmpersands(strInput) {return strInput.replace(”/” + _ampersand + “/g”, “&”);
}
At first, it seems as if it work work fine - concatenate /’s on the value stored in _ampersand and then let JavaScript get to it. Unfortunately, this isn’t how it works. One solution would be to simply hardcode the value of the _ampersand variable into the replace() function, but that’s poor coding. The solution I ended up using is actually extremely simple and it makes perfect sense.
Because replace() requires a regular expression to work its magic, giving it a concatenated string literal will not work. Instead, I ended up first creating a regular expression that includes the _ampersand variable and the global operator, then I passed it into the replace() function. Have a look:
var sRegExInput = new RegExp(_ampersand, “g”);
return strInput.replace(sRegExInput, “&”);
Extremely simple solution to a problem that, in my opinion, shouldn’t have been much of an issue at all. Oh well, at least I know that I wasn’t alone.
