Search code examples
javascriptregexmaskmasking

Masking Processing with regex


I'm going to mask words with regex.

The detection results are as follows.

regex: (?<=.{2}).*(?=.{3})
word : AABBCCC
Result : BB

Use the following code to function normally as shown below.

word.match(new RegExp(regex, 'gi')).forEach(v => {
    word = word.replace(v, '*'.repeat(v.length));
});

Result: AA**CCC

But If the word is BBBBCCC, Result is **BBCCC I want to BB**CCC, How can I get the results I want?


Solution

  • Inside the foreach, you are replacing the match BB (which is in variable v) in the word BBBBCCC, which will replace the first occurrence of BB giving **BBCCC

    It works in the first example for AABBCCC as BB is the only occurrence in the string to be replaced.

    What you can to is use the match in the callback of replace.

    let word = "BBBBCCC";
    const regex = /(?<=.{2}).+(?=.{3})/;
    console.log(word.replace(regex, v => '*'.repeat(v.length)))