JavaScript - string regex backreferences

Posted by quano on Stack Overflow See other posts from Stack Overflow or by quano
Published on 2010-03-15T14:44:32Z Indexed on 2010/03/15 14:59 UTC
Read the original article Hit count: 631

Filed under:
|
|

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"));

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about regex