How can I add a space after every 5th number (as the user types) in input field?
12345 56789 12345 56789
The limitation is that I cannot use any framework like jQuery. This has to be done using plain Javascript or CSS.
I also need to support the ability to hit backspace and correct the number or place cursor anywhere and start correcting with backspace.
The following code is based on the answer here: How to insert space every 4 characters for IBAN registering?
The backspace 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>