views:

134

answers:

2

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"));
+3  A: 

Like this:

str.replace(regex, function(match, $1, $2, offset, original) { return someFunc($2); })
SLaks
Awesome, where can I find more info about this?
quano
https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/String/replace
SLaks
+2  A: 

Pass a function as the second argument to replace:

str = str.replace(/(\$)([a-z]+)/gi, myReplace);

function myReplace(str, group1, group2) {
    return "+" + group2 + "+";
}

This capability has been around since Javascript 1.3, according to mozilla.org.

Sean