ES2019: String.prototype.trimStart / String.prototype.trimEnd

[2019-01-29] dev, javascript, es2019
(Ad, please don’t block)

The proposal “String.prototype.trimStart / String.prototype.trimEnd” (by Sebastian Markbåge) is at stage 4 and therefore part of ECMAScript 2019. This blog post explains how it works.

The string methods .trimStart() and .trimEnd()  

JavaScript already supports removing all whitespace from both ends of a string:

> '  abc  '.trim()
'abc'

The proposal additionally introduces methods for only trimming the start of a string and for only trimming the end of a string:

> '  abc  '.trimStart()
'abc  '
> '  abc  '.trimEnd()
'  abc'

Legacy string methods: .trimLeft() and .trimRight()  

Many web browsers have the string methods .trimLeft() and .trimRight(). Those were added to Annex B of the ECMAScript specification (as aliases for .trimStart() and .trimEnd()): features that are required for web browsers and optional elsewhere.

For the core standard, this proposal chose different names, because “start” and “end” make more sense than “left” and “right” for human languages whose scripts aren’t left-to-right. In that regard, they are consistent with the string methods .padStart() and .padEnd().

What characters count as whitespace?  

For trimming, whitespace means:

  • WhiteSpace code points (spec):
    • <TAB> (CHARACTER TABULATION, U+0009)
    • <VT> (LINE TABULATION, U+000B)
    • <FF> (FORM FEED, U+000C)
    • <SP> (SPACE, U+0020)
    • <NBSP> (NO-BREAK SPACE, U+00A0)
    • <ZWNBSP> (ZERO WIDTH NO-BREAK SPACE, U+FEFF)
    • Any other Unicode character with the property White_Space in category Space_Separator (Zs).
  • LineTerminator code points (spec):
    • <LF> (LINE FEED, U+000A)
    • <CR> (CARRIAGE RETURN, U+000D)
    • <LS> (LINE SEPARATOR, U+2028)
    • <PS> (PARAGRAPH SEPARATOR, U+2029)