The usual Javascript way to add a place on the fly after every 5th digit in the input field

How can I add a space after every 5th number (as user types) in the input field?

12345 56789 12345 56789

The limitation is that I cannot use any infrastructure like jQuery. This must be done using simple Javascript or CSS.

I also need to maintain the ability to remove the backspace and adjust the number or place the cursor anywhere and start fixing with backspace.

The following code is based on the answer here: How to insert a space every 4 characters to register IBAN?

The back space does not work reliably.

function space(str, after) {
  if (!str) {
    return false;
  }
  after = after || 4;
  var v = str.replace(/[^\dA-Z]/g, ''),
    reg = new RegExp(".{" + after + "}", "g");
  return v.replace(reg, function(a) {
    return a + ' ';
  });
}

var el = document.getElementById('pin');
el.addEventListener('keyup', function() {
  this.value = space(this.value, 4);
});
<form>
  <input autocapitalize="off" autocorrect="off" maxlength=20 type="text" placeholder="type the pin" id="pin" name="pin" />
  <script>
  </script>
</form>
Run codeHide result
+4
2

:

input ( keyup/keydown), .

.replace(/\s/g, ''), .replace(/(\d{5})/g, '$1 ') 5- .

, ( ).

document.getElementById('target').addEventListener('input', function (e) {
  e.target.value = e.target.value.replace(/\s/g, '').replace(/(\d{5})/g, '$1 ').trim();
});
<input id="target" type="text"/>
Hide result

, , .

, , selectionEnd, .

document.getElementById('target').addEventListener('input', function (e) {
  var target = e.target, position = target.selectionEnd, length = target.value.length;
  
  target.value = target.value.replace(/\s/g, '').replace(/(\d{5})/g, '$1 ').trim();
  target.selectionEnd = position += ((target.value.charAt(position - 1) === ' ' && target.value.charAt(length - 1) === ' ' && length !== target.value.length) ? 1 : 0);
});
<input id="target" type="text"/>
Hide result

, , ( ). , , ( , , ).

+6

function myFunction() {
    str = document.getElementById('num').value;

    str=str.replace(/\s/g, '');
    if(str.length%5==0){
    
        document.getElementById('num').value+=" ";
    }
}
<input id='num' type="text" onkeyup="myFunction()">
Hide result
0

All Articles