I tried this, how can I make it become 'A1****D4'
let name = "AlB2C3D4";
let s = name.replace(name.substring(2),"*");
We can try a regex replacement with the help of a callback function:
var name = "AlB2C3D4";
var output = name.replace(/^(..)(.*)(..)$/, (a, b, c, d) => b + c.replace(/./g, "*") + d);
console.log(output);
The regex logic here is as follows:
^
from the start of the input(..)
match and capture the first 2 characters(.*)
match and capture the middle portion, excluding(..)
the last two characters (but also capture those)$
end of the stringThen, in the callback/lambda function, we build the output, but we run a replace operation on the middle portion of the input, replacing every character with *
to mask it.