Formatting card numbers

Benchmark created on


Setup

function formatStringByRegex(str) {
  str = str.replace(
    /^([1-9]\/|[2-9])$/g, '0$1/' // 3 > 03/
  ).replace(
    /^(0[1-9]|1[0-2])$/g, '$1/' // 11 > 11/
  ).replace(
    /^([0-1])([3-9])$/g, '0$1/$2' // 13 > 01/3
  ).replace(
    /^(0?[1-9]|1[0-2])([0-9]{2})$/g, '$1/$2' // 141 > 01/41
  ).replace(
    /^([0]+)\/|[0]+$/g, '0' // 0/ > 0 and 00 > 0
  ).replace(
    /[^\d\/]|^[\/]*$/g, '' // To allow only digits and `/`
  ).replace(
    /\/\//g, '/' // Prevent entering more than 1 `/`
  );
}

function formatStringVerbose(str) {
  // Remove all non-digit (0-9), non "/" (/), non white-space (/s) characters
  str = str.trim().replace(/[^0-9/\s]/g, "");

  // For pure number inputs (1224)
  if (!Number.isNaN(Number(str))) {
    //  Format it correctly
    if (str.length > 2) {
      const month = str.slice(0, str.length - 2);
      const year = str.slice(str.length - 2);

      str = `${month} / ${year}`;
    }
  }

  // For inputs with an existing "/"
  if (str.includes("/") && !str.includes(" / ")) {
    // Format it properly
    let [month, year] = str.split("/");
    // Enforce double digit format
    if (month.trim().length === 1) {
      month = `0${month.trim()}`;
    }
    year = `${year.trim()}`;

    str = `${month} / ${year}`;
  }
  // Otherwise insert the slash immediately after the second digit
  else if (str.length >= 2 && str.length < 5) {
    str = `${str.slice(0, 2)} / ${str.slice(2)}`;
  }

  // For inputs that must have some form of MM entered ("6 / " or "06 / ")
  if (str.includes(" / ")) {
    let [month, year] = str.split(" / ");
    // Enforce double digit format
    if (month.trim().length === 1) {
      month = `0${month.trim()}`;
    }
    year = `${year.trim()}`;

    str = `${month} / ${year}`;
  }
}

Test runner

Ready to run.

Testing in
TestOps/sec
By Regex
formatStringByRegex("0627")
ready
Verbose
formatStringVerbose("0627")
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.