Javascript正则表达式:用f($ 1)替换$ 1 [英] Javascript regexp: replacing $1 with f($1)

查看:208
本文介绍了Javascript正则表达式:用f($ 1)替换$ 1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个正则表达式,比如说 /url.com \ /([A-Za-z] +)\ ..html / ,我想要用新字符串$ 1: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.

在JavaScript中执行此操作的最佳方法是什么? 最佳在这里意味着(1)最不容易出错,(2)在空间和速度方面最有效,(3)大多数惯用于JavaScript的特殊组合,特别强调#3。

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.

推荐答案

替换方法可以将函数作为替换参数

例如:

str.replace(/regex/, function(match, group1, group2, index, original) { 
    return "new string " + group1 + ": " + f(group1);
});

这篇关于Javascript正则表达式:用f($ 1)替换$ 1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆