If your string only consists of digits you really need no regex, all you need is a couple of string manipulation methods:
// Adapted from https://stackoverflow.com/a/5450113/3832970, count will always be positive here
function strRepeat(pattern, count) {
var result = '';
while (count > 1) {
if (count & 1) result += pattern;
count >>= 1, pattern += pattern;
}
return result + pattern;
};
var string = "4444333322221111";
console.log(
string.substring(0,4) + strRepeat("#", string.length-8) + string.slice(-4)
)
If you need to mask digits enclosed with four digits on either side in a longer string you may use:
function strRepeat(pattern, count) {
var result = '';
while (count > 1) {
if (count & 1) result += pattern;
count >>= 1, pattern += pattern;
}
return result + pattern;
};
var string = "111109876543210000 abc 1234012345678904321";
console.log(
string.replace(/\d{9,}/g, function(match) {
return match.substr(0,4) + strRepeat("#", match.length-8) + match.slice(-4);
})
)
Here,
/\d{9,}/g
matches all occurrences of nine or more digits
function(match) {...}
- a callback method that takes the regex match and you may manipulate the output here
match.substr(0,4) + "#".repeat(match.length-8) + match.slice(-4)
- concats the first 4 digits, then the digits that need to be replaced with #
are appended, and then the remaining 4 digits are added.
If you want, you may make the regex pattern with capturing groups, it will make the callback method a bit smaller, but will make the regex longer:
function strRepeat(pattern, count) {
var result = '';
while (count > 1) {
if (count & 1) result += pattern;
count >>= 1, pattern += pattern;
}
return result + pattern;
};
var string = "111109876543210000 abc 1234012345678904321";
console.log(
string.replace(/(\d{4})(\d+)(\d{4})/g, function($0, $1, $2, $3) {
return $1 + strRepeat("#", $2.length-8) + $3;
})
)
Here, the (\d{4})(\d+)(\d{4})
pattern will capture 4 digits into Group 1 ($1
), then 1+ digits will be captured into Group 2 ($2
) and then 4 digits will be captured into Group 3 ($3
).