跳到主要内容

`String.prototype.trimStart` 和 `String.prototype.trimEnd`

· 阅读需 1 分钟
Mathias Bynens ([@mathias](https://twitter.com/mathias))

ES2019 引入了 String.prototype.trimStart()String.prototype.trimEnd()

const string = '  hello world  ';
string.trimStart();
// → 'hello world '
string.trimEnd();
// → ' hello world'
string.trim(); // ES5
// → 'hello world'

此功能之前通过非标准的 trimLeft()trimRight() 方法可以使用,这些方法作为新方法的别名保留,以确保向后兼容。

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} 浏览器支持