Exploring ES2018 and ES2019
Please support this book: buy it or donate
(Ad, please don’t block.)

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:

> '  abc  '.trim()
'abc'

The feature 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'

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: