Please support this book: buy it or donate

15. String.prototype.{trimStart,trimEnd}



This chapter describes the ES2019 feature “String.prototype.{trimStart,trimEnd}” (by Sebastian Markbåge).

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

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

  1. > ' abc '.trim()
  2. 'abc'

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

  1. > ' abc '.trimStart()
  2. 'abc '
  3. > ' abc '.trimEnd()
  4. ' abc'

15.2. 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 feature 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().

15.3. 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)