javascript - 替换动态大小的捕获组

标签 javascript node.js regex

我想用星号替换 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/

相关文章:

node.js - 如何在 NodeJS 中使用 fluent-ffmpeg 将图像转换为视频

ruby - gsub 方法和正则表达式(区分大小写和不区分大小写)

javascript - 为什么 ajax 调用中的闭包可以访问外部范围?

javascript - 可调整大小的 <a> 元素

javascript - 将文件插入 Google Drive 的简单、无库的 Javascript 方法

php - 用元素替换每个字符

java - 查找所有带有双方括号的子序列

javascript - 如何为父元素添加类购买单击子按钮Angular 8

Node.js 使用用户名和密码从 URL 下载文件?

javascript - Vuejs更新父数据时更新子组件