I have an input field. I need the input to have the following format: AC-123456789
When I input the characters in the field, after the second character I want the system to add the hyphen automatically just once. The first group of characters has to be a specific letter for the first character and any letter or number for the second character. The second group can only be numbers. If I want to delete using backspace, I should be able to delete also the hyphen.
So far I have:
const transformInput = (input) => {
const inputLength = input.replace('-', '').length;
if (inputLength > 1 && input[2] !== '-') input = `${input.slice(0,2)}-${input.slice(2)}`;
else if (inputLength === 2 && input[2] === '-') input = input.slice(0,2);
return input
}
The problem with the above code is that if I have ‘AB-‘ and I delete with backspace, it won’t delete. I have to add a number like ‘AB-2’ and then it will delete leaving me with ‘AB’. How can the above be improved? Is there an easier way to do it in regex?
I tried using regex as follows but have not been succefull:
const transformInput = (input) => {
return input.replace(/(d[A-Z0-9]{2})(d{1-9})/, '$1-$2')
}
Thanks
3
This seems to cover most cases
Have to save the last keystroke if you want to magically remove the -
when appropriate
It could do with a little more work to handle where the caret is so it doesn’t keep jumping to the end
let lastKey = null;
const transformInput = (input) => {
const inputLength = input.length;
const nodash = input.replaceAll('-', '');
const hasDash = input.includes('-');
if (inputLength < 3 && lastKey === 'Backspace') {
return nodash.slice(0,2);
}
if (inputLength > 2) {
if (nodash.length > 2) {
return `${nodash.slice(0,2)}-${nodash.slice(2)}`;
}
return nodash;
}
return input
}
const input = document.querySelector('input');
input.addEventListener('input', () => {
input.value = transformInput(input.value);
})
input.addEventListener('keydown', (e) => {
lastKey = e.key;
})
<input>