首页 > 解决方案 > `replace()` 函数版本中的命名捕获组

问题描述

我注意到您实际上可以在替换回调中传递您命名的捕获组:

'Yoda said "fear leads to anger."'.replace(
    /(?<pre>\b\w+\b)(?<betwixt> leads to )(?<post>\b\w+\b)/,
    (...args) => {
        let [{pre, betwixt, post}] = args.slice(-1);
        let ani = {fear:'anger',anger:'hate',hate:'suffering'};
        return `${ani[pre]}${betwixt}${ani[post]}`;
    }
)

结果在Yoda said "anger leads to hate.". 至少在铬。

我的问题是这是在哪里定义的?它绝对看起来不规范
它似乎始终是最后一个参数,在string.

我想知道它是一个即将推出的标准,还是我偶然发现的 chrome 开发人员临时有的东西,它会消失:(

标签: javascriptregexcapture-group

解决方案


推荐阅读