Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript RegEx format string containing American Express card number

I'm trying to format a string containing an American Express credit card number using a regular expression. Here's what I'm using for Visa, MasterCard and Discover number formatting, but it obviously doesn't work for American Express:

var formatVisaMasterCardDiscover = function (
    number) {
    return number.split(/(?=(?:\d{4})+($))/).filter(function (
        n) {
        return (n != "");
    }).join("-");
};

So, I'm curious what the regular expression for an Amex number would be. The format should {4}-{6}-{5}. I'd appreciate any help because I couldn't find anything while searching except about how to validate it which is not what I want. I want to format it.

like image 809
Gup3rSuR4c Avatar asked Feb 28 '26 00:02

Gup3rSuR4c


1 Answers

You can use:

var ccNum = '341256789012345';

var ccFmt = ccNum.replace(/\b(\d{4})(\d{6})(\d{5})\b/, '$1-$2-$3');
//=> 3412-567890-12345

RegEx Demo

like image 166
anubhava Avatar answered Mar 02 '26 14:03

anubhava



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!