Javascript正则表达式拆分信用卡号

Javascript正则表达式拆分信用卡号,javascript,regex,Javascript,Regex,我有一个最多包含16位数字的信用卡号,我正在尝试将其拆分:例如(12345678891234567)到:(12345678 9123 4567) 我仍然是一个相当大的RegExp新手,但是我有^(\d{4})(\d{4})?(\d{4})?(\d{4})? 当至少两个组有4个数字时,正则表达式将匹配(1234 5678),但在(1234 56) 如果我添加{2,4}我会得到像(1234 56 78)这样的东西,这是我不想要的 非常感谢您的帮助 更新1: 目标是在用户键入信用卡号时将其拆分: 所以

我有一个最多包含16位数字的信用卡号,我正在尝试将其拆分:例如
(12345678891234567)
到:
(12345678 9123 4567)

我仍然是一个相当大的RegExp新手,但是我有
^(\d{4})(\d{4})?(\d{4})?(\d{4})?

当至少两个组有4个数字时,正则表达式将匹配
(1234 5678)
,但在
(1234 56)

如果我添加
{2,4}
我会得到像
(1234 56 78)
这样的东西,这是我不想要的

非常感谢您的帮助

更新1: 目标是在用户键入信用卡号时将其拆分: 所以
123456
会自动变成:
123456
,等等

更新2: 解释我要做什么的最简单方法是:
然后单击“用卡支付”,然后在“信用卡”字段中键入,您将在键入时看到数字移动。

您不需要拆分它

只要做:

var str = "(1234567891234567)";
var newStr = "(" + str.match(/(\d{4})/g).join(" ") + ")"; //(1234 5678 9123 4567)

只需将原始字符串中的每四位数字替换为相同的数字,后跟空格,如下所示

console.log("123456789101112".replace(/(\d{4}(?!\s))/g, "$1 "));

我本来打算删除这个,因为我的答案并不完全是我在这个问题上想要的,但我不能删除它,所以:

我能够通过以下功能创建所需的功能:

(以下是一个工作示例:)

var信用卡={
名单:[
{
品牌:“美国运通”,
图片:'/images/creditcards/american express.png',
验证:“^3[47][0-9]”,
分离:“^([0-9]{4})([0-9]{6}”)(?:([0-9]{6})([0-9]{5}))?$”,
隐藏:“*********[0-9][0-9][0-9][0-9][0-9]”,
接受:对,,
长度:15
},
{
品牌:“万事达卡”,
图像:'/images/creditcards/mastercard.png',
验证:“^5[1-5][0-9]”,
分隔:“^([0-9]{4})([0-9]{4})([0-9]{4}))([0-9]{4})?”,
隐藏:“******[0-9][0-9][0-9][0-9][0-9]”,
接受:对,,
长度:16
},
{
品牌:“Visa”,
图片:'/images/creditcards/visa.png',
验证:“^4[0-9]”,
分隔:“^([0-9]{4})([0-9]{4})([0-9]{4}))([0-9]{4})?”,
隐藏:“******[0-9][0-9][0-9][0-9][0-9]”,
接受:对,,
长度:16
},
{
品牌:“发现”,
图像:'/images/creditcards/discover.png',
验证:“^6(?:011 | 5[0-9]{2}[0-9]”,
分隔:“^([0-9]{4})([0-9]{4})([0-9]{4}))([0-9]{4})?”,
隐藏:“******[0-9][0-9][0-9][0-9][0-9]”,
接受:错,
长度:16
},
{
品牌:“食客俱乐部”,
图片:'/images/creditcards/diners club international.png',
验证:“^3(?:0[0-5]|[68][0-9])[0-9]”,
分离:“^([0-9]{4})([0-9]{4}”)([0-9]{4})(?:([0-9]{4})([0-9]{4})([0-9]{2}))?$”,
隐藏:“******[0-9][0-9][0-9][0-9][0-9]”,
接受:错,
长度:14
},
{
品牌:“JCB”,
图片:'/images/creditcards/jcb.png',
核实:“^(?:2131 | 1800 | 35[0-9]{3}[0-9]”,
分隔:“^([0-9]{4})([0-9]{4})([0-9]{4}))([0-9]{4})?”,
隐藏:“******[0-9][0-9][0-9][0-9][0-9]”,
接受:错,
长度:16
}
], 
活动:空
};
//关于键控
$('input[name=“creditcard”]')。向下键(函数(e){
//预设数据
var card=$(this).val().replace(/[^0-9]/g',),
trim=$.trim($(this.val().slice(0,-1));
//找到信用卡
对于(var i=0;i 4&&$(this).nextAll('small')。length==0){
//显示错误
$(此)。在(“+”无效信用卡“+”)之后;
}
//预设它们的键
key=creditcards.active!==null?creditcards.active:1;
//如果最后一个字符是字符串,请将其删除
if(e.keyCode==8&&trim!=$(this.val().slice(0,-1)){
//设置新值
$(this).val(trim);
//停止完成
e、 预防默认值();
//返回
返回;
}
//限制卡的长度,允许使用密钥
如果(card.length>=creditcards.list[key].length&&$.inArray(e.keyCode[37,38,39,40,46,8,9,27,13,110,190])===-1&&!e.metaKey&&!e.ctrlKey){
e、 预防默认值();
返回;
}
//如果正则表达式通过,则添加一个空格
if(新RegExp(creditcards.list[key].separation).exec(card)&&e.keyCode>=48&&e.keyCode 1){
存储=card.charAt(card.length-1);
卡片=卡片切片(0,-1);
分离=新的RegExp(creditcards.list[key].separation).exec(card);
}
//如果有分离
如果(分离){
//定义的所有分离的支架
var分离=[];
//删除所有未定义的分隔字段

对于(var i=0;i我认为有许多开发人员使用Stripe实现信用卡交易。下面是一个示例。另外,公认的答案太复杂,其他答案对“美国运通”不起作用

我使用stripe.js的helper函数只是为了检测品牌。所以,即使你没有使用stripe,你也可以使用其余的功能。

Is
1234 5
    var creditcards = { 
        list:[
            {
                brand:          'American Express',
                image:          '/images/creditcards/american-express.png',
                verification:   '^3[47][0-9]',
                separation:     '^([0-9]{4})([0-9]{6})?(?:([0-9]{6})([0-9]{5}))?$',
                hidden:         '**** ****** *[0-9][0-9][0-9][0-9]',
                accepted:       true,
                length:         15
            },
            {
                brand:          'MasterCard',
                image:          '/images/creditcards/mastercard.png',
                verification:   '^5[1-5][0-9]',
                separation:     '^([0-9]{4})([0-9]{4})?([0-9]{4})?([0-9]{4})?$',
                hidden:         '**** **** **** [0-9][0-9][0-9][0-9]',
                accepted:       true,
                length:         16
            },
            {
                brand:          'Visa',
                image:          '/images/creditcards/visa.png',
                verification:   '^4[0-9]',
                separation:     '^([0-9]{4})([0-9]{4})?([0-9]{4})?([0-9]{4})?$',
                hidden:         '**** **** **** [0-9][0-9][0-9][0-9]',
                accepted:       true,
                length:         16
            },
            {
                brand:          'Discover',
                image:          '/images/creditcards/discover.png',
                verification:   '^6(?:011|5[0-9]{2})[0-9]',
                separation:     '^([0-9]{4})([0-9]{4})?([0-9]{4})?([0-9]{4})?$',
                hidden:         '**** **** **** [0-9][0-9][0-9][0-9]',
                accepted:       false,
                length:         16
            },
            {
                brand:          'Diners Club',
                image:          '/images/creditcards/diners-club-international.png',
                verification:   '^3(?:0[0-5]|[68][0-9])[0-9]',
                separation:     '^([0-9]{4})([0-9]{4})?([0-9]{4})?(?:([0-9]{4})([0-9]{4})([0-9]{2}))?$',
                hidden:         '**** **** **[0-9][0-9] [0-9][0-9]',
                accepted:       false,
                length:         14
            },
            {
                brand:          'JCB',
                image:          '/images/creditcards/jcb.png',
                verification:   '^(?:2131|1800|35[0-9]{3})[0-9]',
                separation:     '^([0-9]{4})([0-9]{4})?([0-9]{4})?([0-9]{4})?$',
                hidden:         '**** **** **** [0-9][0-9][0-9][0-9]',
                accepted:       false,
                length:         16
            }
        ], 
        active:null 
    };


  //On Keydown
  $('input[name="creditcard"]').keydown(function(e){


    //Preset Data
    var card = $(this).val().replace(/[^0-9]/g,''),
        trim = $.trim( $(this).val().slice(0,-1) );


    //Find the Credit Card
    for( var i=0; i<creditcards.list.length; i++ ){

      //Check the Type
      if(card.match( new RegExp(creditcards.list[i].verification) )){

        //Set the Active Card
        creditcards.active = i;


        //Add Credit Card Icon
        if( $(this).next('img').length == 0 ){

          //Remove any possible Error
          $(this).next('small').remove();

          //Add the Image
          $(this).after('<img src="'+creditcards.list[i].image+'" alt="'+creditcards.list[i].brand+'" style="height:20px; position:relative; top:5px;" />');

        }


        //If the Credit Card is NOT accepted, Show the Error
        if( !creditcards.list[i].accepted && $(this).nextAll('small').length == 0 ){

          //Show Error
          $(this).next('img').after('<small style="margin-left:5px; color:#F00;">'+'Creditcard Not Accepted'+'</small>');

        }

        //End the Loop
        break;

      }

    }



    //Show Invalid Card
    if( creditcards.active == null && card.length > 4 && $(this).nextAll('small').length == 0 ){

      //Show Error
      $(this).after('<small style="margin-left:5px; color:#F00;">'+'Invalid Credit Card'+'</small>');

    }



    //Preset they Key
    key = creditcards.active !== null? creditcards.active : 1 ;


    //If the Last Character is a String, Remove it
    if( e.keyCode == 8 && trim != $(this).val().slice(0,-1) ){

      //Set the New Value
      $(this).val( trim );

      //Stop from Completing
      e.preventDefault();

      //Return
      return;

    }


    //Limit the Length of the Card, Allow Keys
    if( card.length >= creditcards.list[ key ].length && $.inArray(e.keyCode, [37, 38, 39, 40, 46, 8, 9, 27, 13, 110, 190]) === -1 && !e.metaKey && !e.ctrlKey ){
      e.preventDefault();
      return;
    }

    //Add a Space if the Regex Passes
    if( new RegExp(creditcards.list[ key ].separation).exec( card ) && e.keyCode >= 48 && e.keyCode <= 57 ){
      $(this).val( $(this).val() + ' ' );
    }

    //Return
    return;

  });



























  //On Key up Ensure Card is Validated
  $('input[name="creditcard"]').keyup(function(e){

    //Get the Card
    var card = $(this).val().replace(/[^0-9]/,'');

    //Check if the Card is Active
    if( creditcards.active !== null && !card.match( new RegExp(creditcards.list[ creditcards.active ].verification) ) ){

        //Remove any Existing Error
        $(this).nextAll('small').remove();

        //If Not, Remove the Icon
        $(this).next('img').remove();

        //Set Active to NULL
        creditcards.active = null;

    }else
    if( card.length < 4 ){

      //Remove Invalid Card Error
      $(this).next('small').remove();

    }

  });


































  $('input[name="creditcard"]').on('paste',function(e){

    //Save the Element
    var el    = this;

    //Set Timeout to Run Function
    setTimeout(function(){

      //Save the Card
      var card = $(el).val().replace(/[^0-9]/g,'');

      //Remove all but numbers
      $(el).val( card );

      //Prepare the Keydown Event
      var e = jQuery.Event('keydown',{
        which:    37,
        keyCode:  37
      });


      //Trigger Keydown
      $(el).trigger(e).promise().done(function(e){


        //Preset they Key
        key = creditcards.active !== null? creditcards.active : 1 ;

        //Force the Card Length
        card.substr( 0 , creditcards.list[ key ].length );

        //Separate the Card
        var separation  = new RegExp(creditcards.list[ key ].separation).exec( card ),
            storage     = '';

        //Find the Closest Separation Point
        while( !separation && card.length > 1 ){
          storage     = card.charAt( card.length - 1 );
          card        = card.slice(0,-1);
          separation  = new RegExp(creditcards.list[ key ].separation).exec( card );
        }

        //If there was a Separation
        if( separation ){

          //A Holder for all of the Separation that is defined
          var separated = [];

          //Remove all Undefined Separation Fields
          for( var i=0; i<separation.length; i++){
            if( typeof separation[i] != 'undefined' ) separated.push( separation[i] );
          }

          //Build the String
          var string = separated.slice(1).join(' ') + (storage!=''? ' '+storage : '' )

          //Add the Separated Value
          $(el).val( string )

        }        

      //End $(el).trigger(e).promise().dome(function(e){
      });

    //End setTimeout(function(){
    },0);

  //End $(input[name="creditcard"]
  });
let cardNumber;
let brand = Stripe.card.cardType(value)
if (brand === "American Express") {
  let tempVal = value.replace(/\s/g, '');
  cardNumber = (tempVal.slice(0,4).replace(/(.{4})/g, '$1 ') + 
    tempVal.slice(4,10).replace(/(.{6})/g, '$1 ') +
    tempVal.slice(10,15)).trim();
} else {
  cardNumber = value.replace(/\s/g, '').replace(/(.{4})/g, '$1 ').trim();
}
return cardNumber