I'm trying to hide/replace with * the 6 middle characters of a number, but I'm not getting the desired result.
Input:
54998524154
Expected output:
54*****154
What I tried:
const phone = "54998524154"
phone.replace(/(?<=^[0-9]{2})([0-9]{6})/g, '*')
It returns
54*154
I also tried replaceAll, but it returns the same result.
Edit: I'd like to achieve it using only one * like:
CodePudding user response:
If the input is always going to be 11 chars/digits, you could do something like
phone.replace(/(^\d{2})(\d{6})(\d{3}$)/g, "$1******$3");
Explanation: 3 capture groups:
(^\d{2})
- from the beginning of the string, select 2 digits(\d{6})
- then select 6 digits(\d{3}$)
- Select last 3 digits
Replace pattern:
"$1******$3"
- First capture-group, then 6 asterisks, then 3rd capture-group.
CodePudding user response:
You can do this with the below regex.
console.log("54998524154".replace(/(\d{2})\d{6}/,"$1******"))
In fact, you can do it without regex as well.
var numStr = '54998524154';
console.log(numStr.replace(numStr.substring(2,8), "******"));