0

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?

0

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.