Replace capture group of dynamic size

前端 未结 2 1050
甜味超标
甜味超标 2021-01-15 14:15

I want to replace the first part of regex for a URL with asterisks. Depending on the regex, for example:

Case 1

http://example.com/pat

2条回答
  •  醉话见心
    2021-01-15 14:52

    You may use

    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) + "@";
    }));

    and

    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)); 
    }));

    In case of .replace(/[^@]/gy, '*'), each char other than @ from the start of the string is replaced with * (so, up to the first @).

    In case of .replace(/(.*)@/, function ($0,$1) { return '*'.repeat($1.length) + "@"; }), all chars up to the last @ are captured into Group 1 and then the match is replaced with the same amount of asterisks as the length of the Group 1 value + the @ char (it should be added into the replacement pattern as it is used as part of the consuming regex part).

    The .replace(regex, (_,$1,$2) => `${$1}${'*'.repeat($2.length)}` ) follows the same logic as the case described above: you capture the part you need to replace, pass it into the anonymous callback method and manipulate its value using a bit of code.

提交回复
热议问题