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
- String.prototype.replaceAll — Replaces all occurrences of a substring with another string.
- String.prototype.trimStart — Removes whitespace and line breaks from the start of a string.
- String.prototype.trimEnd — Removes whitespace and line breaks from the end of a string.
Related recipes
In the tutorial
- String methods — Useful string methods in JavaScript: finding a position, reading characters, padStart, repeat, split and join, method chains.