JavaScriptStrings

String.prototype.trim()

Removes whitespace from both ends of a string: spaces, tabs, and newline characters.

Returns
A new string without whitespace on either end (or only at the start or end for trimStart() and trimEnd()).
Changes the original
No
On this page

Example

#
JavaScript
const nickname = '   Mia   '

console.log(`[${nickname}]`)
console.log(`[${nickname.trim()}]`)
Console
[ Mia ]
[Mia]

Definition and usage

#

The trim() method returns a new string without whitespace at the start and end. It removes spaces, tabs, newline characters, and other Unicode spacing, such as a non-breaking space. Spaces between words are left untouched.

It is most often used on data typed by users. A stray space at the end of a nickname or email address can break a comparison or a login, and a field filled with nothing but spaces should be treated as empty.

When you want to clean up only one side, use trimStart() (the beginning) or trimEnd() (the end). All three methods take no arguments, return a new string, and leave the original unchanged.

Syntax

#
Syntax
string.trim()
string.trimStart()
string.trimEnd()

More examples

#
Checking for an empty field
JavaScript
function isEmpty(value) {
  return value.trim().length === 0
}

console.log(isEmpty('   '))
console.log(isEmpty('\n\t'))
console.log(isEmpty(' Leo '))
Console
true
true
false
trimStart() and trimEnd()
JavaScript
const line = '   let points = 10   '

console.log(`[${line.trimStart()}]`)
console.log(`[${line.trimEnd()}]`)
Console
[let points = 10 ]
[ let points = 10]
Cleaning up a list of tags
JavaScript
const raw = ' html ,  css,javascript  '
const tags = raw.split(',').map((tag) => tag.trim())

console.log(tags)
Console
['html', 'css', 'javascript']

Browser support

#

Widely available

Works in all modern browsers, phones included. You can use it without worry.

  • Chrome
  • Edge
  • Firefox
  • Safari

Good practices

#
  • Trim form data before validating and saving it, not only when displaying it.
  • trim() does not remove double spaces inside the text. For that, use replace(/\s+/g, " ").

Related entries

#

Spotted a mistake or missing an example? Write to us.