js中str.trim方法

· 1 min read

string字符串有trim方法,但trim并非只是处理首尾空格,最近使用时发现有认识上的错误。因此mark下

根据MDN中介绍可以看到,trim处理的是首尾的white space+ line terminators

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

而空格只是其中一种white space。那具体有哪些字符呢

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

所以说字符串中首尾包含上述字符在trim后都会被删除。

举例子

这里测试下几个字符

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

只处理空格

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

写在最后

之所以发现该问题还是因为程序中字符串被被赋值为\r,而str.trim后会是空字符串,这个不符合预期。因此才重新看下trim逻辑,发现了理解有误