Javascript String Replace with Backreferences
There are hundreds of examples of how to use the Javascript String Replace function. However these are often very simple examples and do not fully show the potential power of this easy to use method. So when I came across a more complex real-life problem that required the use of javascript string replace - I thought it might be useful to others to share it.
The problem I was dealing with, was a messed up cookie string. The string contained data blocks divided by the "|", the problem was that a recent programming change had caused this divider to not be inserted correctly. Fortunately, the data blocks all started with a date (YYYY-MM-DD) and always ended with a number. I needed to run a regex to insert the "|" back into the data automatically. Here is the replace function...
var newcookie=oldCookieStr.replace(/(\d{1})(20\d{2}-\d{2}-\d{2})/g, "$1|$2");
The first parameter of the replace function is the RegEx. This regex contains two backreference groups, defined by the brackets(). The first is (\d{1}) , if the string layout is correct, this character would be a "|" and therefore not match - which is what we want, if it is a number, it is missing the divider and it will match. The second group simply matches the date and puts the data into the second backreference group. The "g" tells the regex to match ALL possible matches.
The second parameter of the replace function is the replacement string. And this is the neat part; We can use the backreference groups from the regex to reconstruct the original string, but with our divider now neatly inserted. There are two backreference groups defined and these are accessed using $1 and $2, so reconstructing the replacement string is a simple process of recombining the backreferences with the divider between $1|$2. Simple! and very powerful.
