Javascript, replace and regex

I learned something new today while trying to do a regex replace in Javascript.

The first thing was about the replace method. I learned from John Resig's "Secrets of the JavaScript ninja" (a great book which I recommend, by the way) that you can also dynamically search and replace a regular expression.

Like in this snippet:

var result = myText.replace(regex, function (match) {
    // you can do something with the match
    return someValue;
});

This can be amazingly useful! For example, I used it to evaluate dynamic expressions, searching for the 'w' character, and replaced it with the target's width, or searching for a percentage and replacing it with the absolute value, making me capable of interpreting stuff like '100%-w' on the fly, with a simple eval of a mathematical expression (1024-400, let's say).

What I did not know was that my match was the entire pattern, not just the group.

var testString = 'test a B 3';

var newString = testString.replace(/test ([a-z])/g, function (match) {
    console.log(match); // will print 'test a'
    return match;
});

In a situation similar to the one above, I needed simply 'a' and I did not understood why I got 'test a' as a result. It turns out if you need a reference to a particular group, you need to declare it as a parameter:

var testString = 'test a B 3';

var newString = testString.replace(/([a-z]) ([A-Z]) ([0-9])/g, function (match, groupOne, groupTwo, groupThree) {
    console.log(match); // will print 'a B 3'
    console.log(groupOne); // will print 'a'
    console.log(groupTwo); // will print 'B'
    console.log(groupThree); // will print '3'
    return match;
});

I found out thanks to the wonderful folks at StackOverflow, helpful as usual.

And with that occasion, I also learned another thing, even more important: you should always read the whole documentation carefully! This part was very well documented on the Mozilla Developer Network, but I never did more than just skim trough the text. Silly mistake, one that I'll try to never make again