Encodera

Thanks for reading!

Donate to the site — we work hard for you.

JavaScript reference

String.prototype.trim

Removes whitespace from both ends of a string.

Available since: ES5

Syntax

str.trim()

Return value

stringA new string without whitespace at its ends.

Examples

Spaces and a line break at the ends are removed:

console.log('[' + '  text \n'.trim() + ']');

Output:

[text]

trimStart() strips only the start, trimEnd() only the end:

console.log('[' + '  text  '.trimStart() + ']');
console.log('[' + '  text  '.trimEnd() + ']');

Output:

[text  ]
[  text]

Notes

The method leaves whitespace inside the string alone. Form input is worth passing through trim() before validation.

See also

Related recipes

In the tutorial

  • String methods — Useful string methods in JavaScript: finding a position, reading characters, padStart, repeat, split and join, method chains.

Thanks for reading!

Donate to the site — we work hard for you.