Cover image for Javascript method to return flags of cards.

Javascript method to return flags of cards.

renanduart3 profile image Renan Duarte ・1 min read

I'm not really sure which cards we have to deal with in nowadays, but i got this problem to evaluate correctly the cards before sending the number to the gateway that not have something like this (or another solution more professional) to get flag card based on the number, so i've searched, compiled in my snippets and now wrinting here to ... just write, so i hope this could help someone out there 😁

by default, the flag returned is 'visa' if nothings match.

PS: The truth is that i have no idea how this regular expression works.

   returnflag('2014 7722409 8894');

   function returnflag(cardNumber) {
        cardNumber = cardNumber.toString().replace(/[^0-9]+/g, '');
        const cards = {
            visa: /^4[0-9]{12}(?:[0-9]{3})?/,
            mastercard: /^(((51)|(52)|(53)|(54)|(55))\d{0,14})/,
            diners: /^3(?:0[0-5]|[68][0-9])[0-9]{11}/,
            amex: /^3[47][0-9]{13}/,
            discover: /^6(?:011|5[0-9]{2})[0-9]{12}/,
            hipercard: /^(606282\d{10}(\d{3})?)|(3841\d{15})/,
            elo: /^((((636368)|(438935)|(504175)|(451416)|(636297))\d{0,10})|((5090)|(5067)|(4576)|(4011))\d{0,12})/,
            jcb: /^(?:2131|1800|35\d{3})\d{11}/,
            aura: /^(5078\d{2})(\d{2})(\d{11})$/

        for (let flag in cards) {
            if (cards[flag].test(cardNumber)) {
                return flag;
        return 'visa';

Posted on by:


Editor guide