Skip to content
Advertisement

How to format expiry credit card date MM/YYYY

I need to format an expiry date for credit card in the following format MM/YYYY using a regex which looks like this ^(0[1-9]|1[0-2])/?([0-9]{4})$ but when it comes to add slashes it groups everything in 2. The question here is how do I add slashes only after first 2 instead of each 2?

const formatCardDate = (item) => {
  let input = item;

  if (/^(0[1-9]|1[0-2])/?([0-9]{4})$/.test(input)) {
    input = input.match(new RegExp(".{1,2}", "g")).join("/");
  }

  return input;
};

Advertisement

Answer

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement