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

前端 未结 3 1046
余生分开走
余生分开走 2021-01-19 07:26

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

3条回答
  •  盖世英雄少女心
    2021-01-19 07:55

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

提交回复
热议问题