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

Date and Time related aggregation functions ($year, $month, $dayOfMonth, $hour, $minute, $second, $dayOfWeek, $dateToString, $dateSubtract, $dateAdd, $isoWeek, $isoDayOfWeek, $dateTrunc, $dateFromString, $dateToParts, $dateFromParts, $dateDiff, $week)

In this blog post, we will explore Date/Time-related Aggregation Functions in MongoDB. MongoDB provides a robust set of aggregation operator...