Javascript 替换动态大小的捕获组

Javascript 替换动态大小的捕获组,javascript,node.js,regex,Javascript,Node.js,Regex,我想用星号替换URL的正则表达式的第一部分。根据正则表达式,例如: 案例1 http://example.com/path1/path2?abcd=>http://example.com/path1/********** Regex 1:/^(https?:\/\/.+\/.+\/path1\/?)(.+/),但我希望组2中的每个字符分别替换为* 或 案例2 person@example.com=>******@example.com Regex 2 /^(+.+)(@.+)$/,同样,我希望第

我想用星号替换URL的正则表达式的第一部分。根据正则表达式,例如:

案例1

http://example.com/path1/path2?abcd
=>
http://example.com/path1/**********

Regex 1
/^(https?:\/\/.+\/.+\/path1\/?)(.+/
),但我希望组2中的每个字符分别替换为
*

案例2

person@example.com
=>
******@example.com

Regex 2

/^(+.+)(@.+)$/
,同样,我希望第一个捕获组中的所有字符都单独替换为
*

我曾尝试使用捕获组,但后来,我只剩下
*@example.com

let email=`person@example.com`;
设正则表达式=/^(+.+)(@.+)$/;
console.log(email.replace(regex,'*$2'))您可以使用

let email=`person@example.com`;
设regex=/[^@]/gy;
console.log(email.replace(regex,'*');
//或
console.log(email.replace(/(.*)@/,函数($0,$1){
返回“*”。重复($1.length)+“@”;

}));您可以使用粘性标志y(但Internet Explorer不支持):

但最简单的方法(在任何地方都支持)是使用函数作为替换参数

s = s.replace(/^(https?:\/\/.+\/path1\/?)(.*)/, function (_, m1, m2) {
    return m1 + '*'.repeat(m2.length);
});

对于第二种情况,只需检查当前位置后是否有
@

s = s.replace(/.(?=.*@)/g, '*');
s = s.replace(/.(?=.*@)/g, '*');