DEV Community

Cover image for Javascript method to return flags of cards.
Renan Duarte
Renan Duarte

Posted on

4 2

Javascript method to return flags of cards.

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';
    }

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay