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

前端 未结 3 1048
余生分开走
余生分开走 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:46

    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 */;
    });
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-19 08:08

    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);
    });
    
    0 讨论(0)
提交回复
热议问题