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"));
back-references are regular expression commands which refer to a previous part of the matched regular expression. Back-references are specified with backslash and a single digit (e.g. ' \1 '). The part of the regular expression they refer to is called a subexpression, and is designated with parentheses.
If your regular expression has named capturing groups, then you should use named backreferences to them in the replacement text. The regex (?' name'group) has one group called “name”. You can reference this group with ${name} in the JGsoft applications, Delphi, .
backreference (plural backreferences) (regular expressions) An item in a regular expression equivalent to the text matched by an earlier pattern in the expression.
The name can contain letters and numbers but must start with a letter. (? P<x>abc){3} matches abcabcabc. The group x matches abc.
Like this:
str.replace(regex, function(match, $1, $2, offset, original) { return someFunc($2); })
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With