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()andtrimEnd()). - Changes the original
- No
Example
#const nickname = ' Mia '
console.log(`[${nickname}]`)
console.log(`[${nickname.trim()}]`)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
#string.trim()
string.trimStart()
string.trimEnd()More examples
#function isEmpty(value) {
return value.trim().length === 0
}
console.log(isEmpty(' '))
console.log(isEmpty('\n\t'))
console.log(isEmpty(' Leo '))const line = ' let points = 10 '
console.log(`[${line.trimStart()}]`)
console.log(`[${line.trimEnd()}]`)const raw = ' html , css,javascript '
const tags = raw.split(',').map((tag) => tag.trim())
console.log(tags)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, usereplace(/\s+/g, " ").
Related entries
#- String.prototype.split()Splits a string into an array of pieces based on a separator: a character, a string, or a regular expression.
- String.prototype.lengthThe length of a string, i.e. the number of UTF-16 code units. The property is read-only.
- String.prototype.padStart()Pads a string on the left with the given text until it reaches the specified length. Perfect for leading zeros.
- String.prototype.toLowerCase()Returns a copy of the string converted to lowercase. Useful for comparisons and normalizing data.
- String.prototype.trimStart()Removes whitespace only from the start of a string. The end of the text stays unchanged.
- String.prototype.trimEnd()Removes whitespace only from the end of a string, including trailing newline characters.
Spotted a mistake or missing an example? Write to us.