Last active
May 15, 2026 07:30
-
Star
(205)
You must be signed in to star a gist -
Fork
(48)
You must be signed in to fork a gist
-
-
Save DiegoSalazar/4075533 to your computer and use it in GitHub Desktop.
Luhn algorithm in Javascript. Check valid credit card numbers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Takes a credit card string value and returns true on valid number | |
| function valid_credit_card(value) { | |
| // Accept only digits, dashes or spaces | |
| if (/[^0-9-\s]+/.test(value)) return false; | |
| // The Luhn Algorithm. It's so pretty. | |
| let nCheck = 0, bEven = false; | |
| value = value.replace(/\D/g, ""); | |
| for (var n = value.length - 1; n >= 0; n--) { | |
| var cDigit = value.charAt(n), | |
| nDigit = parseInt(cDigit, 10); | |
| if (bEven && (nDigit *= 2) > 9) nDigit -= 9; | |
| nCheck += nDigit; | |
| bEven = !bEven; | |
| } | |
| return (nCheck % 10) == 0; | |
| } |
A shitty one-liner:
const luhn = numbers => numbers.split('').map((value, index) => index % 2 === 0 ? Number(value) * 2 <= 9 ? Number(value) * 2 : Number(Number(`${Number(value) * 2}`.split('')[0]) + Number(`${Number(value) * 2}`.split('')[1])) : Number(value)).reduce((a, b) => a + b).toString().split('')[1] === '0';Great Luhn implementation ๐
One small edge case: an empty string or whitespace input may return true after stripping non-digits. You might want to add a guard like:
if (!value) return false;
This helps avoid false positives.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The code can be rewritten as:
Or even cleaner