Credit Card Number in JS
Match 16-digit credit card numbers with optional spaces or hyphens between groups of 4.
Try it in the JS tester →Pattern
regexJS
\b(?:\d{4}[\s\-]?){3}\d{4}\b (flags: g)JavaScript / ECMAScript code
jsJavaScript
const re = new RegExp("\\b(?:\\d{4}[\\s\\-]?){3}\\d{4}\\b", "g");
const input = "4111 1111 1111 1111";
const matches = [...input.matchAll(re)];
console.log(matches.map(m => m[0]));Uses `String.prototype.matchAll` for global iteration (Node 12+ / all modern browsers).
How the pattern works
Three groups of 4 digits with optional space/hyphen separators, followed by a final 4-digit group. Word boundaries prevent partial matches.
Examples
Input
4111 1111 1111 1111Matches
4111 1111 1111 1111
Input
4111-1111-1111-1111Matches
4111-1111-1111-1111
Input
4111111111111111Matches
4111111111111111