Get card type with JavaScript

Posted: 08-11-2023 | Views: 55
Get card type with JavaScript

Method 1
function getCardType(cardNumber) {
  try {
    let number = String(cardNumber);
    let re = new RegExp("^4");
    if (number.match(re) != null) return "visa";
    re = new RegExp("^(34|37)");
    if (number.match(re) != null) return "amex";
    re = new RegExp("^5[1-5]");
    if (number.match(re) != null) return "mastercard";
    re = new RegExp("^6011");
    if (number.match(re) != null) return "discover";

    return "visa";
  } catch (error) {
    console.log("getCardType error: ", error);
  }
}

console.log(getCardType("416951032586")); // visa
Method 2
function getCardType(cardNumber) {
  // Define regular expressions for various card types
  var cardPatterns = {
    visa: /^4[0-9]{12}(?:[0-9]{3})?$/,
    mastercard: /^5[1-5][0-9]{14}$/,
    amex: /^3[47][0-9]{13}$/,
    discover: /^6(?:011|5[0-9]{2})[0-9]{12}$/,
    dinersclub: /^3(?:0[0-5]|[68][0-9])[0-9]{11}$/,
    jcb: /^(?:2131|1800|35\d{3})\d{11}$/
  };

  for (var card in cardPatterns) {
    if (cardPatterns[card].test(cardNumber)) {
      return card;
    }
  }

  return "Unknown";
}

// Example usage
var cardNumber = "4111111111111111"; // Replace with the actual card number
var cardType = getCardType(cardNumber);
console.log("Card Type: " + cardType);

Add comment