JavaScript RegEx: Format string with dynamic length to block format

前端 未结 3 1279
情深已故
情深已故 2021-01-21 08:45

The following RegEx formats given string to following output block pattern:

123 456 78 90 (= 3 digits 3 digits 2 digits 2 digits )

RegEx:



        
3条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-21 09:14

    You can use

    const rx = /^(\d{3})(\d{1,3})?(\d{1,2})?(\d{1,2})?$/;
    
    $('body').on('input', '.info', function(e) {
      this.value = this.value.replace(/\s+/g,'')
       .replace(/^(\d{10}).*/, '$1')
        .replace(rx, (_,w,x,y,z) =>
          z ? `${w} ${x} ${y} ${z}` :
          y ? `${w} ${x} ${y}` :
          x ? `${w} ${x}` : w);
    });
    
    

    The ^(\d{3})(\d{1,3})?(\d{1,2})?(\d{1,2})?$ regex will perform live formatting together with the callback function used as the replacement argument. The first three digits are obligatory, the second, third and fourth blocks are optional, but contain at least one digit. Spaces are only added if there is at least one digit in the block. The number is reformatted each time the number is edited:

    • .replace(/\s+/g,'') removes the added spaces
    • .replace(/^(\d{10}).*/, '$1') keeps just the first ten digits if there are more

提交回复
热议问题