我想用星号替换 URL 的正则表达式的第一部分。取决于正则表达式,例如:
案例一
http://example.com/path1/path2?abcd
=> http://example.com/path1/************
正则表达式 1:/^(https?:\/\/.+\/path1\/?)(.+)/
但我想要每个字符第 2 组将单独替换为 *
或
案例二
person@example.com
=> ******@example.com
正则表达式 2
/^(.+)(@.+)$/
,类似地,我希望 first 捕获组中的所有字符都单独替换为 *
我曾尝试使用捕获组,但后来,我只剩下 *@example.com
let email = `person@example.com`;
let regex = /^(.+)(@.+)$/;
console.log(email.replace(regex, '*$2'));
let url = `http://example.com/path1/path2?abcd`;
let regex = /^(https?:\/\/.+\/path1\/?)(.+)/;
console.log(url.replace(regex, '$1*'));
最佳答案
你可以使用
let email = `person@example.com`;
let regex = /[^@]/gy;
console.log(email.replace(regex, '*'));
// OR
console.log(email.replace(/(.*)@/, function ($0,$1) {
return '*'.repeat($1.length) + "@";
}));
和
let url = `http://example.com/path1/path2?abcd`;
let regex = /^(https?:\/\/.+\/path1\/?)(.*)/gy;
console.log(url.replace(regex, (_,$1,$2) => `${$1}${'*'.repeat($2.length)}` ));
// OR
console.log(url.replace(regex, function (_,$1,$2) {
return $1 + ('*'.repeat($2.length));
}));
在 .replace(/[^@]/gy, '*')
的情况下,字符串开头的 @
以外的每个字符都被替换为*
(因此,直到第一个 @
)。
如果是 .replace(/(.*)@/, function ($0,$1) { return '*'.repeat($1.length) + "@"; })
,直到最后一个 @
的所有字符都被捕获到第 1 组,然后用与第 1 组值 + @
字符的长度相同数量的星号替换匹配项(它应该被添加到替换模式中,因为它被用作消费正则表达式部分的一部分)。
.replace(regex, (_,$1,$2) => `${$1}${'*'.repeat($2.length)}` )
遵循与上述案例:您捕获需要替换的部分,将其传递给匿名回调方法并使用一些代码操作其值。
关于javascript - 替换动态大小的捕获组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56826088/