问题描述
是否可以在JavaScript中获取正则表达式捕获组的字符串长度?我想用星号替换实际密码捕获组(即$ 2)的长度。
let urlRedacted = url.replace(/mongodb:\/\/(.+):(.+)@(.+)/,'mongodb://$1:*****@$3');
上面只是用硬编码的五个*****
代替了密码($ 2)的实际长度。
解决方法
使用回调函数将第二个组添加到变量中,然后.replace
将所有*
个组包含在该变量中:
const url = 'mongodb://foo:bar@baz';
const censor = str => str.replace(/./g,'*');
// could also do
// const censor = str => '*'.repeat(str.length);
let urlRedacted = url.replace(
/mongodb:\/\/(.+):(.+)@(.+)/,(_,g1,g2,g3) => `mongodb://${g1}:${censor(g2)}@${g3}`
);
console.log(urlRedacted);
,
如果可以使用后视,则不需要 lambda:
const url = 'mongodb://foo:bar@baz';
let urlRedacted = url.replace(/(?<=mongodb:\/\/.+:[^@]*)[^@]/g,'*');
console.log(urlRedacted); // mongodb://foo:***@baz
见proof。
说明
--------------------------------------------------------------------------------
(?<= look behind to see if there is:
--------------------------------------------------------------------------------
mongodb: 'mongodb:'
--------------------------------------------------------------------------------
\/ '/'
--------------------------------------------------------------------------------
\/ '/'
--------------------------------------------------------------------------------
.+ any character except \n (1 or more times
(matching the most amount possible))
--------------------------------------------------------------------------------
: ':'
--------------------------------------------------------------------------------
[^@]* any character except: '@' (0 or more
times (matching the most amount
possible))
--------------------------------------------------------------------------------
) end of look-behind
--------------------------------------------------------------------------------
[^@] any character except: '@'