Я думаю, вы имели в виду это
function maskIt(str, keep) {
var len = str.length,
re = new RegExp("(.{" + keep + "})(.{" + (len - keep * 2) + "})(.{" + keep + "})", "g")
console.log(re)
return str.replace(re, function(match, a, b, c) {
return a + ("" + b).replace(/./g, "*") + c
});
}
console.log(
maskIt("1234567890", 4),
maskIt("Apple", 1)
)
В качестве прототипа:
String.prototype.maskIt = function(keep) { // don't use arrow or lose "this"
const re = new RegExp("(.{" + keep + "})(.{" + (this.length - keep * 2) + "})(.{" + keep + "})", "g");
return this.replace(re, (match, a, b, c) => a + ("" + b).replace(/./g, "*") + c);
}
console.log(
"1234567890".maskIt(4),
"Apple".maskIt(1)
)