A user pasting an email address often brings a space along with it. Two minutes later the sign-in fails, the address still looks perfectly fine on screen, and nobody understands why.
trim clears that whole category of problems, provided it is called in the right place.
Definition
trim hands back a new String stripped of the whitespace sitting before the first visible character and after the last one. Inner spaces are kept, and the starting string stays intact.
const input = " contact@believemy.com ";
console.log(input.length); // 25
console.log(input.trim().length); // 21
console.log(input.trim()); // "contact@believemy.com"
console.log(" a b ".trim()); // "a b", the inner space staysLike every string method, trim changes nothing: its return value has to be picked up. Writing input.trim(); alone on a line produces no effect and no error message, which makes it a hard omission to spot.
What trim really removes
The method does not stop at the ordinary space. It removes every whitespace character and every line break.
- The ordinary space the one from the space bar.
- The tab written
\t, common in files pasted out of a spreadsheet. - Line breaks
\nand\r, which linger at the end of a file line. - The non-breaking space the
\u00A0character, brought in by most copies and pastes from a web page.
console.log(JSON.stringify("\n\t Hello \r\n".trim())); // "Hello"
console.log(JSON.stringify("\u00A0Hello\u00A0".trim())); // "Hello"One exception is worth knowing: the zero-width space \u200B, invisible yet very much there, is not a whitespace character as far as the standard goes. trim leaves it in place, and a comparison then fails for no visible reason.
trimStart and trimEnd
The two variants handle one side only. They mostly serve to clean file lines without flattening an indentation that carries meaning.
const line = " level 2 ";
console.log(JSON.stringify(line.trimStart())); // "level 2 "
console.log(JSON.stringify(line.trimEnd())); // " level 2"Frequently asked questions
Where should trim be called?
As close to the input as possible, right before validating or saving, and on every text field. Pairing it with toLowerCase on an email address also avoids duplicate accounts that differ by a single capital letter.
Is cleaning up in the browser enough?
No. A request can arrive without going through your form, from another client or a testing tool. Cleaning in the browser improves the experience, but server-side validation is the only one that guarantees what gets stored.
How do you also remove duplicate spaces inside?
trim never touches the middle. To normalize the whole thing, chain it with a String.replace() on a pattern: text.trim().replace(/\s+/g, " ") brings any run of spaces, tabs or line breaks down to a single space.