JavaScript String trim() Method
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 point | Name | Abbreviation | Description | Escape sequence |
U+0009 | Character tabulation | Horizontal tabulation | \t | |
U+000B | Line tabulation | Vertical tabulation | \v | |
U+000C | Form feed | Page breaking control character (Wikipedia). | \f | |
U+0020 | Space | Normal space | ||
U+00A0 | No-break space | Normal space, but no point at which a line may break | ||
U+FEFF | Zero-width no-break space | When not at the start of a script, the BOM marker is a normal whitespace character. | ||
Others | Other Unicode space characters | Characters in the “Space_Separator” general category |
Line terminators
Code point | Name | Abbreviation | Description | Escape sequence |
U+000A | Line Feed | New line character in UNIX systems. | \n | |
U+000D | Carriage Return | New line character in Commodore and early Mac systems. | \r | |
U+2028 | Line Separator | Wikipedia | ||
U+2029 | Paragraph Separator | Wikipedia |
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.