Need some help with a regex to match middle x number of digits in javascript ie.
Numbers
123456 3234231234
3234231234
Expected Outcome x=3
123456 323***1234
323***1234
- The mask * length can vary ie 3 -> ***
- If space is present it should select the middle numbers in the second set
So far what I have is /(?<=\s).{3}/g
which just gets the first few digits and does not work when space is not present, this is how it shows up,
123456 ***4231234 *(first 3 digits)*
42342341234 *(does not match as required above)*
CodePudding user response:
Because you're dealing with a small set of possible widths, you can develop a sub-expression for each size and or them together. One possible expression for only odd lengths might be:
(?:.* )?\b(?:(.{3})|.(.{3}).|..(.{3})..|...(.{3})...|....(.{3})....)\b
Although it will double the size, it shouldn't be difficult to expand the expression to include even lengths as well.
CodePudding user response:
I dont think regex are the right tool for the 100% of the job
You can use it to segment and operate your string, and then use string functions to replace the parts you need with *
check this out
function mask(value, digits, masker = "*"){
// divides the string if has a space
let components = value.match(/(\d*?\s?)(\d )$/);
// only will mask the last part
let target = components[2];
let leading = components[1];
// calculate the middle of the string and the part to replace
let length = target.length;
let lengthBeforeMask = Math.floor((length/2)-(digits/2));
let lengthAfterMask = Math.ceil((length/2)-(digits/2));
// use templates to concatenate the string and substring to replace the parts with the mask
return `${leading}${target.substring(0,lengthBeforeMask)}${masker.repeat(digits)}${target.substring(length - lengthAfterMask, length)}`;
}
// use it
mask("123456 3234231234", 3); // "123456 323***1234"
mask("3234231234", 3); // "323***1234"
mask("3234231234", 5); // "32*****234"
// also can change the mask just ;)
mask("12345", 3, "&"); // "1&&&5"