String.prototype.trimStart
/ String.prototype.trimEnd
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.
.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'
.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()
.
For trimming, whitespace means:
<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)White_Space
in category Space_Separator
(Zs
).<LF>
(LINE FEED, U+000A)<CR>
(CARRIAGE RETURN, U+000D)<LS>
(LINE SEPARATOR, U+2028)<PS>
(PARAGRAPH SEPARATOR, U+2029)