Home > Software engineering >  How to write a RegEx to format a CC number
How to write a RegEx to format a CC number

Time:01-19

I've almost got this function working as desired. I'm passing a string that will have certain characters replaced(12 numbers in this first case) with dashes to help hide the CC number, while keeping the last four #'s of the string. I could use some help in replacing a string that's already got certain characters in it.

This function works well if I pass in a string like '9876 5432 1098 1005', but I also need to test a string if it already has characters to hide the CC numbers, like this '************2006'. If I can solve for these two cases, that would be amazing. Thanks in advance for the help :)

export const formatCard = (acct: string, hide = false): string => {
  const regExFormula = /\b(?:\d{4}[ -]?){3}(?=\d{4}\b)/gm;
  const subst = `---- ---- ---- `;

  if (hide === true) {
    return acct.replace(regExFormula, subst);
  }
  return acct;
};

CodePudding user response:

You can use

const formatCard = (acct, hide = false) => {
  const regExFormula = /(?:\b(?:\d{4}[ -]?){3}|\* )(?=\d{4}\b)/g;
  const subst = `---- ---- ---- `;

  if (hide === true) {
    return acct.replace(regExFormula, subst);
  }
  return acct;
};

console.log(formatCard("************6789", true));
console.log(formatCard("1234 5678 1234 5678", true));

Now, the (?:\b(?:\d{4}[ -]?){3}|\* ) part either matches a word boundary and then three occurrences of four digits followed with an optional space or hyphen, or one or more asterisks.

If you want a purely regex solution you can capture last four digits and then replace with the hyphen mask placeholders to the group values:

const formatCard = (acct, hide = false) => {
  if (hide === true) {
    return acct.replace(/.*(\d)\D*(\d)\D*(\d)\D*(\d).*/, '---- ---- ---- $1$2$3$4');
  }
  return acct;
}

console.log(formatCard("************6789", true));
console.log(formatCard("4124-5460-6-9-5----4", true));
console.log(formatCard("1234 5678 1234 5678", true));

See this regex demo.

  •  Tags:  
  • Related