The following RegEx formats given string to following output block pattern:
123 456 78 90 (= 3 digits 3 digits 2 digits 2 digits )
RegEx:
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