Sometime ago, I was working on a piece of client-side code that needed to encode some data before invoking an Ajax request. Next, it needed to decode the response data.

While doing this, I experienced a nuance in JavaScript’s replace() function that required a little bit of effort in order for it to work with the degree of flexibility I needed.

My code was sending a variable-length query string of data to the server. The problem was that the ampersands were not being properly decoded on the server-side after the initial Ajax request.

I was storing the encoded representation of the ampersand in a local variable named _ampersand and had a function that accepted the full query string to be sent to the server, encode the data, perform some additional processing, and then return it.

Essentially, the function looked like this:

function encodedData(strInput) {
    // irrelevant code removed...
    return strInput.replace(/&/g, _ampersand);

This worked for sending the data across the wire, but decoding the response proved to be another challenge.

Because I was performing a global replacement of the ampersand token, I was using the ‘g’ operator to manage all occurrences but actually using the variable in the replace() function didn’t work as expected.

Originally, I was trying to do this:

// this does not work...
function restoreAmpersands(strInput) {
    return strInput.replace('/' + _ampersand + '/g', '&');

Trying to concatenate the /’s on the value stored in the _ampersand doesn’t work: replace() requires a regular expression to work its magic. Since JavaScript was casting the result of the concatenation as a string, it wasn’t working.

So, I first created a regular expression that included the _ampersand variable along with the global operator. Then I passed that particular regular expression into the replacement code:

var sRegExInput = new RegExp(_ampersand, 'g');
return strInput.replace(sRegExInput, '&');

And that took care of it. Easy enough.