Javascript Program for masking email and phone number

  • Here is the two different function that receive email and phone and return masked value.


    export const maskEmail = (email) => {
        if (email) {

            // Split the email into local and domain parts
            const atIndex = email.indexOf('@');
            if (atIndex === -1) {
                // If no '@' symbol is found, return the original email
                return email;
            }

            const localPart = email.substring(0, atIndex);
            const domainPart = email.substring(atIndex);

            // Determine how many characters to mask in the local part
            let maskedPartLength = localPart.length - 3;
            if (maskedPartLength < 1) {
                // If the local part is too short, adjust the number of visible characters
                maskedPartLength = localPart.length > 1 ? 1 : 0;
            }

            // Create the masked part
            const maskedPart = '*'.repeat(maskedPartLength);
            const visiblePart = localPart.substring(0, localPart.length - maskedPartLength);

            // Combine the visible part, masked part, and domain part
            return `${visiblePart}${maskedPart}${domainPart}`;
        } else {
            return "****@****.com"
        }
    }

    export const maskPhoneNumber = (phoneNumber) => {
        if (phoneNumber) {

            // Check if the phone number has less than 4 digits
            if (phoneNumber.length <= 4) {
                return phoneNumber; // Return the original if too short to mask
            }

            // Mask all but the last four digits
            const visiblePart = phoneNumber.slice(-4);
            const maskedPartLength = phoneNumber.length - 4;
            const maskedPart = '*'.repeat(maskedPartLength);

            // Combine the masked part and the visible part
            return `${maskedPart}${visiblePart}`;
        } else {
            return "**** **** ****"
        }
    }


No comments:

Post a Comment

Primitive Types in TypeScript

In TypeScript, primitive types are the most basic data types, and they are the building blocks for handling data. They correspond to simple ...