I have an input field of length 14 into which the user types a value. As the user types into it, I would like a space to be added automatically after first 2 characters and then after next 3 characters and then after next 3 characters. so if the user wants to enter 12345678901, it should be formatted to 12 345 678 901.
Also when user uses backspace to clear the characters, the space should automatically be removed. So in the above case when the cursor reaches 9 and user hits backspace, the cursor should move two places to left clearing 9 and the space before it.
I tried following the credit card formatting here Format credit card number but couldn't understnd how it is done. The code from above link is
formatInput(event: any) {
var v = event.value.replace(/\s+/g, '').replace(/[^0-9]/gi, '')
var matches = v.match(/\d{4,16}/g);
var match = matches && matches[0] || ''
var parts = []
for (let i=0, len=match.length; i<len; i+=4) {
parts.push(match.substring(i, i+4))
}
if (parts.length) {
(<HTMLInputElement>document.getElementById("txtInput")).value =
parts.join(' ')
} else {
(<HTMLInputElement>document.getElementById("txtInput")).value
= event.value;
}
}
The above code generates spaces after every 4 digits. My requirement is to accept any characters and generate spaces after first 2 characters and then after next 3 characters and then after next 3 characters. Please help me out with this.