References

Beginner-friendly references for web development, with live, editable examples.

The JavaScript string.trim() method

Method JavaScript All modern browsers Updated
Quick answer

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

Live 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() or trimEnd() 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?
It removes whitespace (spaces, tabs, newlines) from the start and end of a string and returns a new string. The middle is left alone.
How do I remove spaces from user input?
Call trim() on the value: input.value.trim(). This clears leading and trailing whitespace.
How do I trim only one side of a string?
Use trimStart() for the beginning or trimEnd() for the end.
Does trim() remove spaces inside the string?
No, only at the ends. To collapse inner whitespace use str.replace(/\s+/g, " ").