Skip to content
Tutorials Center
My learning

Topics

JavaScript Reference ยท String

String.prototype.trim()

Reference for JavaScript String.prototype.trim(): remove whitespace and line terminators from both ends of a string, with what counts as whitespace and examples.

The trim() method returns a copy of a string with whitespace removed from both the start and the end. Whitespace in the middle is not touched. The characters removed include spaces, tabs, newlines and carriage returns, plus other Unicode space characters such as the non-breaking space.

It is the first thing to do with text typed into a form field, read from a file or split from a line: stray spaces and a trailing newline are the most common source of "it looks identical but does not match" bugs.

JavaScript
"  hello  ".trim(); // "hello"

Try it

JS Cleaning up input

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS What counts as whitespace

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Syntax

JavaScript
string.trim()

This method takes no parameters.

Return value: a new string with leading and trailing whitespace and line terminators removed. If there is nothing to remove, the contents are the same. A string that is entirely whitespace gives an empty string.

Exceptions: none for strings.

Usage notes

  • Whitespace here means the ECMAScript WhiteSpace and LineTerminator characters: space, tab, vertical tab, form feed, non-breaking space, the byte order mark U+FEFF, other Unicode "Space Separator" characters, and the line terminators \n, \r, U+2028 and U+2029.
  • Zero-width space (U+200B) is not removed. It is invisible but is not classified as whitespace, so text copied from some web pages can still look "dirty" after trim().
  • Only the ends. To collapse inner runs of spaces use replace(/\s+/g, " ").
  • Directional versions: trimStart() and trimEnd() trim just one side.
  • Immutable: a new string is returned; remember to assign it.
  • Not for other characters. trim() cannot remove commas or dashes; use a regular expression like /^-+|-+$/g for that.
  • Validation: an input that contains only spaces becomes "" after trim(), which is a handy way to reject blank values: if (!value.trim()).
  • Non-strings do not have this method. Convert first with String(value) when a value may be a number or null.

Browser support

String.prototype.trim() has been supported in every browser for a very long time.