Skip to content

Instantly share code, notes, and snippets.

@nitin2953
Created October 23, 2025 09:18
Show Gist options
  • Select an option

  • Save nitin2953/52b4cbc40722d012fbec0ed4449a2c8d to your computer and use it in GitHub Desktop.

Select an option

Save nitin2953/52b4cbc40722d012fbec0ed4449a2c8d to your computer and use it in GitHub Desktop.
Simple regex to only allow letters in any laguage but not any number or emoji characters. There is also a fix for caret position when replacing text in an input field. Please don't ask any question about regex, I'm not a expert here, this code came from many trial & error. Have suggestion, please comment. Demo: https://happywishyou.pages.dev/wis…
/*
* \u200B: ZERO WIDTH SPACE
* \u200C: ZERO WIDTH NON-JOINER
* \u200D: ZERO WIDTH JOINER
* \uFE00-\uFE0F: VARIATION SELECTOR 1 to 16
* \u2139: INFO EMOJI
* \u20E3: Number Emoji COMBINING ENCLOSING KEYCAP (joiner for number emoji)
*/
const regex = /[^\s\p{L}\p{M}]|[\u200B\u200C\u200D\uFE00-\uFE0F\u2139\u20E3]/gu;
function cleanString(name) {
return name.replaceAll(regex, ''); // Remove disallowed characters
}
function cleanNameString(name) {
return name.replaceAll(regex, '').replace(/\s+/g, ' ').trim(); // Remove disallowed characters
}
/* ********************* Clean Input *********************** */
nameInput = document.getElementById('name-input'),
function cleanInput() {
const originalCaretPosition = nameInput.selectionStart;
let value = nameInput.value;
let cleanValue = cleanString(value) // Remove disallowed characters
cleanValue = cleanValue.replace(/^\s+/, ' '); // only 1 leading space
cleanValue = cleanValue.replace(/\s{2,}$/, ' '); // only 1 trailing space
cleanValue = cleanValue.replaceAll(/\s{3,}/g, ' '); // max 2 spaces b/w words
// Update the input value only if diallowed chracters were entered & are now removed
if (value !== cleanValue) {
const modifiedCaretPosition = Math.max(originalCaretPosition - (value.length - cleanValue.length), 0);
nameInput.value = cleanValue;
nameInput.setSelectionRange(modifiedCaretPosition, modifiedCaretPosition);
}
cleanName = cleanNameString(cleanValue); // ONLY 1 space b/w words & no spaces around
}
cleanInput()
nameInput.addEventListener('input', cleanInput);
nameInput.addEventListener('change', cleanInput); // Don't know if needed
window.addEventListener('load', cleanInput);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment