javascript

How to get first 2 and last 2 characters in javascript


I tried this, how can I make it become 'A1****D4'

let name = "AlB2C3D4";
let s = name.replace(name.substring(2),"*");

Solution

  • 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:

    Then, 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.