Skip to content

Instantly share code, notes, and snippets.

@erdum
Last active December 19, 2023 06:05
Show Gist options
  • Save erdum/650ad7891a467482c5bd1b48a8c2a649 to your computer and use it in GitHub Desktop.
Save erdum/650ad7891a467482c5bd1b48a8c2a649 to your computer and use it in GitHub Desktop.
Format input field dynamically to add hyphens after specific length of characters
const addHyphens = (inputField) => {
inputField.addEventListener('input', (event) => {
let value = event.target.value.replace(/-/g, '');
let formattedValue = '';
for (let i = 0; i < value.length; i++) {
if (i === 5 || i === 12) {
formattedValue += '-';
}
formattedValue += value[i];
}
event.target.value = formattedValue;
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment