ES2019 introduces String.prototype.trimStart()
and String.prototype.trimEnd()
:
const string = ' hello world ';
string.trimStart();
// → 'hello world '
string.trimEnd();
// → ' hello world'
string.trim(); // ES5
// → 'hello world'
This functionality was previously available through the non-standard trimLeft()
and trimRight()
methods, which remain as aliases of the new methods for backward compatibility.
const string = ' hello world ';
string.trimStart();
// → 'hello world '
string.trimLeft();
// → 'hello world '
string.trimEnd();
// → ' hello world'
string.trimRight();
// → ' hello world'
string.trim(); // ES5
// → 'hello world'
String.prototype.trim{Start,End}
support #
- Chrome: 自 66 版本开始支持
- Firefox: 自 61 版本开始支持
- Safari: 自 12 版本开始支持
- Node.js: 自 8 版本开始支持
- Babel: 支持