Users paste text from anywhere, chatbots, Word, web pages, and it arrives full of invisible characters and odd spacing. If you store it raw, that junk corrupts your data. Here is how to sanitize it.
Why sanitize on input
Text from a user's clipboard commonly contains:
- zero-width and invisible characters
- non-breaking and exotic spaces
- smart quotes and em dashes
- leading and trailing whitespace
Stored raw, these break search, comparisons, uniqueness checks, and exports later. Sanitizing at the boundary, when the text comes in, keeps your database clean and saves you from chasing invisible bugs downstream.
A basic sanitize step
A minimal normalization in JavaScript:
function sanitize(s){
return s
.replace(/[\u200B-\u200D\u2060\uFEFF]/g, '') // zero-width + BOM
.replace(/[\u00A0\u2000-\u200A\u202F\u205F\u3000]/g, ' ') // exotic spaces -> normal
.replace(/[\u201C\u201D]/g, '"').replace(/[\u2018\u2019]/g, "'") // smart quotes
.replace(/[ \t]+/g, ' ') // collapse spaces
.trim();
}
Run it on submit, or in a paste event handler if you want to clean as the user pastes.
Handle the paste event
To clean at paste time, intercept the event, sanitize the pasted text, and insert the clean version:
field.addEventListener('paste', function(e){
e.preventDefault();
const text = (e.clipboardData || window.clipboardData).getData('text/plain');
document.execCommand('insertText', false, sanitize(text));
});
This gives users immediate, clean input without changing what they see.
Sanitizing rich paste
If your field accepts rich text, also strip dangerous and messy HTML: allow a small set of semantic tags (lists, bold, headings), remove all attributes and inline styles, and unwrap everything else. This removes the Word and web clutter and protects against injected markup at the same time.
For quick fixes, use a cleaner
For a one-off or for testing what your users are pasting, run the text through a cleaner like textscrubr to see and strip the hidden characters. It is a fast way to confirm what your sanitize step should be catching.
The principle
Sanitize at the boundary. Clean text on the way in, once, and everything downstream, storage, search, export, stays clean.