`String.prototype.trimStart` 和 `String.prototype.trimEnd`
· 閱讀時間約 1 分鐘
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'