JavaScript String trim() Method

· 2 min read

String objects have a trim method, but trim doesn’t just handle leading and trailing spaces. I recently discovered I had a misconception about this when using it, so I’m making a note here.

According to the MDN introduction, trim handles whitespace + line terminators at the beginning and end:

A new string representing str stripped of whitespace from both its beginning and end. Whitespace is defined as white space characters plus line terminators.

Space is just one type of white space. So what specific characters are included?

White space

Code pointNameAbbreviationDescriptionEscape sequence
U+0009Character tabulationHorizontal tabulation\t
U+000BLine tabulationVertical tabulation\v
U+000CForm feedPage breaking control character (Wikipedia).\f
U+0020SpaceNormal space
U+00A0No-break spaceNormal space, but no point at which a line may break
U+FEFFZero-width no-break spaceWhen not at the start of a script, the BOM marker is a normal whitespace character.
OthersOther Unicode space charactersCharacters in the “Space_Separator” general category

Line terminators

Code pointNameAbbreviationDescriptionEscape sequence
U+000ALine FeedNew line character in UNIX systems.\n
U+000DCarriage ReturnNew line character in Commodore and early Mac systems.\r
U+2028Line SeparatorWikipedia
U+2029Paragraph SeparatorWikipedia

So strings containing any of the above characters at the beginning or end will have them removed after trim().

Examples

Let’s test a few characters:

console.log('\r123\r'.trim().length) // 3
console.log('\n123\n'.trim().length) // 3
console.log('    \n123\n'.trim().length) // 3

Handling Only Spaces

console.log('    \n123\n'.replace(/^\x20+|\x20+$/g,'').length)

Conclusion

I discovered this issue because in my program, a string was assigned the value \r, and after str.trim() it became an empty string, which didn’t meet expectations. This prompted me to revisit the trim logic and realize my understanding was incorrect.