SME-Web/src/utlity/maskUtils.ts

83 lines
2.9 KiB
TypeScript

import { MASKCHARACTER } from "../components/process/processStepTwo/rightSideBar/RightSideBar";
const type_all = (str: string, changeWith: string): string => {
return str.replace(/./g, changeWith);
};
const type_last_four = (str: string, changeWith: string): string => {
str = str.slice(0, -4).replace(/./g, "*") + str.slice(-4);
return str.replace(/\*/g, changeWith);
};
const type_credit_card = (str: string, changeWith: string): string => {
if (str.length !== 15 && str.length !== 16) return str;
const last4 = str.slice(-4);
const masked = str.slice(0, -4).replace(/\d/g, changeWith);
if (str.length === 16) {
// Format: XXXX XXXX XXXX 1234
return masked.slice(0, 4) + " " + masked.slice(4, 8) + " " + masked.slice(8, 12) + " " + last4;
} else {
// 15-digit (Amex): XXXX XXXXXX X1234
return masked.slice(0, 4) + " " + masked.slice(4, 10) + " " + masked.slice(10, 11) + last4;
}
};
const type_national_insurance = (str: string, changeWith: string): string => {
// str = str.slice(0, -1).replace(/[A-Za-z0-9]/g, "*") + str.slice(-1);
// return str.replace(/\*/g, changeWith);
return `${changeWith.repeat(2)} ${changeWith.repeat(2)} ${changeWith.repeat(2)} ${changeWith.repeat(2)} ${str.slice(-1)}`
};
const type_social_security = (str: string, changeWith: string): string => {
// Expecting 9-digit string like "123456789"
const cleaned = str.replace(/\D/g, ""); // remove non-digit characters
if (cleaned.length !== 9) return str;
const part3 = cleaned.slice(5);
return `${changeWith.repeat(3)}-${changeWith.repeat(2)}-${part3}`;
};
const type_social_insurance = (str: string, changeWith: string): string => {
const cleaned = str.replace(/\D/g, "");
if (cleaned.length !== 9) return str;
const part3 = cleaned.slice(6);
return `${changeWith.repeat(3)} ${changeWith.repeat(3)} ${part3}`;
};
const maskUtils = (type: string, original: string, changeWith: string): string => {
switch (changeWith) {
case MASKCHARACTER.ASTERISK:
changeWith = "*";
break;
case MASKCHARACTER.DOT:
changeWith = ".";
break;
case MASKCHARACTER.X:
changeWith = "x";
break;
}
switch (type) {
case "ALL":
return type_all(original, changeWith);
case "LAST_FOUR":
return type_last_four(original, changeWith);
case "CREDIT_CARD":
return type_credit_card(original, changeWith);
case "NATIONAL_INSURANCE":
return type_national_insurance(original, changeWith);
case "SOCIAL_SECURITY":
return type_social_security(original, changeWith);
case "SOCIAL_INSURANCE":
return type_social_insurance(original, changeWith);
default:
return original;
}
};
export default maskUtils;