Sometimes, we want to identify card type from card number with JavaScript.
In this article, we’ll look at how to identify card type from card number with JavaScript.
How to identify card type from card number with JavaScript?
To identify card type from card number with JavaScript, we can check against regexes for card numbers of different types of cards.
For instance, we write:
const getCardType = (number) => {
if (number.match(new RegExp("^4")) !== null) {
return "Visa";
} else if (/^(5[1-5][0-9]{14}|2(22[1-9][0-9]{12}|2[3-9][0-9]{13}|[3-6][0-9]{14}|7[0-1][0-9]{13}|720[0-9]{12}))$/.test(number)) {
return "Mastercard";
} else if (number.match(new RegExp("^3[47]")) !== null) {
return "AMEX";
} else if (number.match(new RegExp("^(6011|622(12[6-9]|1[3-9][0-9]|[2-8][0-9]{2}|9[0-1][0-9]|92[0-5]|64[4-9])|65)")) !== null) {
return "Discover";
} else if (number.match(new RegExp("^36")) !== null) {
return "Diners";
} else if (number.match(new RegExp("^30[0-5]")) !== null) {
return "Diners - Carte Blanche";
} else if (number.match(new RegExp("^35(2[89]|[3-8][0-9])")) !== null) {
return "JCB";
} else if (number.match(new RegExp("^(4026|417500|4508|4844|491(3|7))")) !== null) {
return "Visa Electron";
}
return "";
}
console.log(getCardType('5105105105105100'))
console.log(getCardType('4111111111111111'))
We define the getCardType
function that takes the card number
.
Then we use a series of if-else statements to check whether number
matches regexes for different card types with the string’s match
method.
If match
returns anything other than null
, that means the number
matches the given regex pattern.
Therefore, 'Mastercard'
and 'Visa'
are logged since we the first number is a test Mastercard number and the 2nd is a test Visa card number.
Conclusion
To identify card type from card number with JavaScript, we can check against regexes for card numbers of different types of cards.