Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript - string regex backreferences

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")); 
like image 811
quano Avatar asked Mar 15 '10 14:03

quano


People also ask

What are Backreferences in regex?

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.

How do I reference a capture group in regex?

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, .

What is Backrefs?

backreference (plural backreferences) (regular expressions) An item in a regular expression equivalent to the text matched by an earlier pattern in the expression.

How do you name a group in regex?

The name can contain letters and numbers but must start with a letter. (? P<x>abc){3} matches abcabcabc. The group x matches abc.


2 Answers

Like this:

str.replace(regex, function(match, $1, $2, offset, original) { return someFunc($2); }) 
like image 91
SLaks Avatar answered Oct 04 '22 00:10

SLaks


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.

like image 26
Sean Avatar answered Oct 04 '22 02:10

Sean