String.prototype.trimStart()

String 值的 trimStart() 方法从该字符串的开头删除空格并返回一个新字符串,而不修改原始字符串。trimLeft() 是该方法的别名。

¥The trimStart() method of String values removes whitespace from the beginning of this string and returns a new string, without modifying the original string. trimLeft() is an alias of this method.

Try it

语法

¥Syntax

js
trimStart()

trimLeft()

参数

¥Parameters

没有任何。

¥None.

返回值

¥Return value

表示 str 的新字符串从开头(左侧)删除了空格。空白定义为 空白 个字符加 行终止符 个字符。

¥A new string representing str stripped of whitespace from its beginning (left side). Whitespace is defined as white space characters plus line terminators.

如果 str 的开头没有空格,仍然返回一个新字符串(本质上是 str 的副本)。

¥If the beginning of str has no whitespace, a new string is still returned (essentially a copy of str).

混叠

¥Aliasing

trim() 标准化后,发动机也实现了非标准方法 trimLeft。然而,为了与 padStart() 保持一致,当该方法标准化时,其名称被选择为 trimStart。出于 Web 兼容性原因,trimLeft 仍然作为 trimStart 的别名,并且它们引用完全相同的函数对象。在某些引擎中,这意味着:

¥After trim() was standardized, engines also implemented the non-standard method trimLeft. However, for consistency with padStart(), when the method got standardized, its name was chosen as trimStart. For web compatibility reasons, trimLeft remains as an alias to trimStart, and they refer to the exact same function object. In some engines this means:

js
String.prototype.trimLeft.name === "trimStart";

示例

¥Examples

使用 trimStart()

¥Using trimStart()

以下示例从 str 的开头修剪空白,但不从结尾修剪空白。

¥The following example trims whitespace from the start of str, but not from its end.

js
let str = "   foo  ";

console.log(str.length); // 8

str = str.trimStart();
console.log(str.length); // 5
console.log(str); // 'foo  '

规范

Specification
ECMAScript Language Specification
# sec-string.prototype.trimstart

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看