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

别说谁变了你拦得住时间么 提交于 2019-12-04 03:49:10

问题


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.


回答1:


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



回答2:


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



回答3:


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



来源:https://stackoverflow.com/questions/4180363/javascript-regexp-replacing-1-with-f1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!