JavaScript - string regex backreferences

quano picture quano · Mar 15, 2010 · Viewed 49.2k times · Source

You can backreference like this in JavaScript:

var str = "123 $test 123";
str = str.replace(/(\$)([a-z]+)/gi, "$2");

This would (quite silly) replace "$test" with "test". But imagine I'd like to pass the resulting string of $2 into a function, which returns another value. I tried doing this, but instead of getting the string "test", I get "$2". Is there a way to achieve this?

// Instead of getting "$2" passed into somefunc, I want "test"
// (i.e. the result of the regex)
str = str.replace(/(\$)([a-z]+)/gi, somefunc("$2"));

Answer

SLaks picture SLaks · Mar 15, 2010

Like this:

str.replace(regex, function(match, $1, $2, offset, original) { return someFunc($2); })