eNeMetcH eNeMetcH - 7 months ago 41
jQuery Question

JS/jQuery - Transform phone number and email to show only first and last characters

How do I dynamically transform phone numbers and email from an API response to hide the non extreme character?

For Ex:

  1. The Invoice will be sent to you email: n*****1@gmail.com

  2. OTP will be sent to your phone number: 7******213

The API contains key:values so I will get phone# and email isolated, so no need to sieve them from a larger string.Also phone numbers are always 10 digits and I need to show the 1st and last three digits.

PS: I suck at regex :(


Consider the following extended solution using String.split, String.replace, String.slice and ES6 String.repeat functions:

var email = "nick_tomson1@gmail.com", phone = "7112459213";

function transformEntry(item, type) {
    switch (type) {
        case 'email':
            var parts = item.split("@"), len = parts[0].length;
            return email.replace(parts[0].slice(1,-1), "*".repeat(len - 2));
        case 'phone':
            return item[0] + "*".repeat(item.length - 4) + item.slice(-3);
            throw new Error("Undefined type: " + type);

console.log(transformEntry(email, 'email'));  // n**********1@gmail.com
console.log(transformEntry(phone, 'phone'));  // 7******921