javascript - JSjQuery - Transform phone number and email to show only first and last characters - Stack Overflow

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

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*****[email protected]

  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 :(

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*****[email protected]

  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 :(

Share Improve this question asked Jun 15, 2016 at 19:46 enemetchenemetch 5222 gold badges9 silver badges23 bronze badges 2
  • Use substr() to get the parts of the string you want. Or use a regular expression. – Barmar Commented Jun 15, 2016 at 20:27
  • 2 You can hide part of phone or email in browser but API response contains full info. (And interested user can find it). Do it on server side. – Alex Kudryashev Commented Jun 15, 2016 at 20:52
Add a ment  | 

2 Answers 2

Reset to default 5

To convert the phone numbers use this:

'740-344-4484'.replace(/(\d{1})(.*)(\d{3})/, '$1******$3')

And finally, to convert the emails:

'[email protected]'.replace(/(\w{1})(.*)(\w{1})@(.*)/, '$1******$3@$4')

The outputs are, respectively:

"7******484" 
"S******[email protected]"

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

var email = "[email protected]", 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);
       default: 
            throw new Error("Undefined type: " + type);
    }        
}

console.log(transformEntry(email, 'email'));  // n**********[email protected]
console.log(transformEntry(phone, 'phone'));  // 7******213

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745187628a4615711.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信