LearnFrenzy
Sign in Take a free test

Strings · Strings Coding Problems · Question 8

Mask a card number and an email address in JavaScript Solution, output & explanation

  • Program
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 8 Back to Exercise

Show only the last 4 digits of a card number (grouped in fours) and mask an email as a***a@domain.

Solution
main.js
function maskCard(number) {
  const digits = number.replace(/\D/g, "");                    // remove spaces and dashes
  const masked = "*".repeat(digits.length - 4) + digits.slice(-4);
  return masked.match(/.{1,4}/g).join(" ");
}

function maskEmail(email) {
  const [user, domain] = email.split("@");
  if (user.length <= 2) return `${user[0]}*@${domain}`;
  return `${user[0]}${"*".repeat(user.length - 2)}${user.at(-1)}@${domain}`;
}

console.log(maskCard("4111-1111-1111-1234"));
console.log(maskEmail("ashasharma@example.com"));
console.log(maskEmail("ab@lf.in"));

Output Verified by running it on Node.js

**** **** **** 1234
a********a@example.com
a*@lf.in

slice(-4) keeps the last four digits and repeat builds the stars. match(/.{1,4}/g) splits the result into groups of four. Short user names get a fixed mask so nothing is revealed.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links