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

时间:2014-08-03 04:57:43

标签: javascript regex

我的信用卡号码最多包含16位数字,我试图将其分开:Ex。 (1234567891234567)至:(1234 5678 9123 4567)

我还是一个非常棒的RegExp新手,但我有^(\d{4})(\d{4})?(\d{4})?(\d{4})?

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

会失败

如果我添加{2,4},我会收到(1234 56 78)这些我不想要的内容。

非常感谢任何帮助

更新1: 目标是在用户输入时将信用卡号拆分: 因此123456会自动变为:1234 56等等。

更新2: 解释我想要做的最简单的方法是:https://stripe.com/docs/tutorials/checkout  然后点击用卡付款,然后输入"信用卡"字段,您将在键入时看到数字移动。

3 个答案:

答案 0 :(得分:7)

只需将原始字符串中的每四个数字替换为相同的数字后跟一个空格,如此

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

答案 1 :(得分:5)

我打算删除这个,因为我的回答并不是我在这个问题中寻找的内容,但我不能删除它:

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

(这是一个工作示例:http://jsfiddle.net/7vH6T/

    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"]
  });

答案 2 :(得分:0)

您无需拆分它。

只是做:

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

DEMO