Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript regexp: replacing $1 with f($1)

I have a regular expression, say /url.com\/([A-Za-z]+)\.html/, and I would like to replace it with new string $1: f($1), that is, with a constant string with two interpolations, the captured string and a function of the captured string.

What's the best way to do this in JavaScript? 'Best' here means some combination of (1) least error-prone, (2) most efficient in terms of space and speed, and (3) most idiomatically appropriate for JavaScript, with a particular emphasis on #3.

like image 247
Charles Avatar asked Dec 05 '22 00:12

Charles


2 Answers

The replace method can take a function as the replacement parameter.

For example:

str.replace(/regex/, function(match, group1, group2, index, original) { 
    return "new string " + group1 + ": " + f(group1);
});
like image 74
SLaks Avatar answered Dec 19 '22 03:12

SLaks


When using String.replace, you can supply a callback function as the replacement parameter instead of a string and create your own, very custom return value.

'foo'.replace(/bar/, function (str, p1, p2) {
    return /* some custom string */;
});
like image 38
deceze Avatar answered Dec 19 '22 04:12

deceze