Strings
trim()
Removes spaces from the edges of a string.
Why it exists
A user copies an email address from a message and accidentally grabs a space; hits space after typing a password; pastes text with a line break at the end. You can't see it, but to a program "anna@mail.com " and "anna@mail.com" are different strings: sign-in fails, search finds nothing, the "field is empty" check lets a string of spaces through. trim() is the first thing done to any input.
Where it's used
- Form fields: email, username, name — before checking and saving.
- Checking "the field isn't empty":
if (text.trim() === ""). - Parsing lines from a file, where a line break is left at the end.
- A search query:
query.trim(), so a trailing space breaks nothing.
Syntax
string.trim()
string.trimStart()
string.trimEnd()Examples
" hello ".trim(); // → "hello"
" a b ".trim(); // → "a b"const email = " anna@mail.com ";
email === "anna@mail.com"; // → false
email.trim() === "anna@mail.com"; // → truefunction isBlank(text) {
return text.trim() === "";
}
isBlank(" "); // → true
isBlank(" a "); // → false"hello\n".trim(); // → "hello"
" → ".trimStart(); // → "→ "Results after // → aren't just written down — an automatic check runs and verifies them before every site update.
Why it works this way
trim looks at both ends of the string and drops every "whitespace" character: an ordinary space, a tab \t, a line break \n, a non-breaking space and others. As soon as a non-whitespace character appears, trimming from that side stops.
That's why trim doesn't touch spaces between words: " a b " becomes "a b".
Like other string methods, trim returns a new string. There are one-sided versions: trimStart() and trimEnd().
Traps
How it differs from…
replace()andreplaceAll()replace/replaceAll remove characters anywhere in the string;
trimonly at the edges.
When to pick something else
Don't apply trim to text where edge spaces matter: passwords, formatted code, indented poems. To remove spaces inside a string, use replaceAll or split/join.