简体   繁体   中英

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.

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

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 */;
});

.replace() takes a function for the replace, like this:

var newStr = string.replace(/url.com\/([A-Za-z]+)\.html/, function(all, match) {
  return match + " something";
});

You can transform the result however you want, just return whatever you want the match to be in that callback. You can test it out here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM