The JavaScript string.trim() method
The trim() method removes whitespace — spaces, tabs, line breaks — from both ends of a string and returns a new one. " hello ".trim() gives "hello". It only touches the ends, never the middle, and it's the standard first step when handling form input.
Overview
trim() strips whitespace off the start and end of a string. Spaces, tabs, newlines — all gone from the edges, while the inside is left exactly as it was. The original isn't changed; you get a clean new string back.
Its number-one job is cleaning user input. People put stray spaces before and after what they type all the time, and an untrimmed value breaks comparisons, validation and lookups in ways that are maddening to debug. Calling input.value.trim() the moment you read a form field saves a lot of grief.
If you only want to trim one side, trimStart() and trimEnd() do exactly that. Note that trim() only removes whitespace at the ends — to collapse multiple spaces inside a string, use replace() with a regex like /\\s+/g.
Syntax
const clean = str.trim()
" hello ".trim() // "hello"
Example
<pre id="out" style="font:15px ui-monospace,monospace"></pre>
<script>
const raw = ' alice@example.com ';
const clean = raw.trim();
document.getElementById('out').textContent =
'raw length: ' + raw.length + '\n' +
'clean: "' + clean + '"';
// raw length: 23 / clean: "alice@example.com"
</script>
Best practices
- Trim form input as soon as you read it —
field.value.trim()— to avoid stray-space bugs. - Use
trimStart()ortrimEnd()when you only want to clean one side. - Remember it only affects the ends; use a regex replace() to collapse inner whitespace.
- Use the return value — the original string is unchanged.
Frequently asked questions
What does trim() do in JavaScript?
How do I remove spaces from user input?
trim() on the value: input.value.trim(). This clears leading and trailing whitespace.How do I trim only one side of a string?
trimStart() for the beginning or trimEnd() for the end.Does trim() remove spaces inside the string?
str.replace(/\s+/g, " ").