/    Sign up×
Bounties /Pin to ProfileBookmark

What is the method for determining the type of a Credit card based on its number?

+ 1,000
Copy linkTweet thisAlerts:
Jul 02.2022
to post a answer
Full-stack DeveloperJavaScript

1 Replies

Copy linkTweet thisAlerts:
@toddDec 02.2022 — To detect the type of a Credit card based on its number in JavaScript, you can use a regular expression to match the pattern of the Credit card number against known patterns for different card types. Here's an example:


function detectCardType(cardNumber) {
// American Express card numbers start with 34 or 37 and have 15 digits
if (/^(34|37)\d{13}$/.test(cardNumber)) {
return 'American Express';
}

// Visa card numbers start with 4 and have 13 or 16 digits
if (/^4\d{12}(?:\d{3})?$/.test(cardNumber)) {
return 'Visa';
}

// Mastercard card numbers start with 51, 52, 53, 54, or 55 and have 16 digits
if (/^5[1-5]\d{14}$/.test(cardNumber)) {
return 'Mastercard';
}

// Discover card numbers start with 6011, 622126-622925, or 644-649 and have 16 digits
if (/^(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)\d{12}$/.test(cardNumber)) {
return 'Discover';
}

// If none of the above patterns match, the card type cannot be determined
return 'Unknown';
}


To use this function, you would call it with a Credit card number as the argument, like this:


const cardType = detectCardType('4111 1111 1111 1111');
console.log(cardType); // 'Visa'


This function uses regular expressions to match the Credit card number against known patterns for different card types. If the number matches a pattern, the function returns the name of the card type. If the number does not match any known pattern, the function returns 'Unknown'.
×

Success!

Help @hq spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 2.27,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Samric24,
tipped: article
amount: 1000 SATS,

tipper: Anonymous,
tipped: article
amount: 10 SATS,

tipper: @neststayhome,
tipped: article
amount: 1000 SATS,
)...