How to insert space every 4 characters for IBAN registering?

前端 未结 9 1723
感情败类
感情败类 2020-11-29 03:28

I\'m really new in JavaScript and I would like to add to my input text, space insertion for IBAN account registering.

9条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-29 04:04

    You have to capture each group of 4 digits and then put a space between each group.

      $('input').blur(function () {
      //Replace each group 4 digits  with a group plus a space
            var reformat = this.value.replace(/(\d{4})/g, function(match){
            return match + " ";
            });
            this.value = reformat;
        })
    

    And this one updates the element while typing

     //Keys pressed 0 times
    var downed = 0; 
    $('#test').keydown(function (g) {
        if(g.code.match("^Digit")){
            downed++;
          console.log(g)
        }
    
        if(downed == 1){
            var reformat = this.value.replace(/(\d{4}\s*)/g, function(match){
                //Strip spaces
                if(match.match(/\s/)){return match;}
                return match + " ";
        });
        console.log(reformat);
        this.value = reformat; 
        //Start recount
            downed = 0;
        }
    });
    

    Check out the fiddle

提交回复
热议问题