String.prototype.trimEnd()

String 值的 trimEnd() 方法删除该字符串末尾的空格并返回一个新字符串,而不修改原始字符串。trimRight() 是该方法的别名。

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

Try it

语法

¥Syntax

js
trimEnd()

trimRight()

参数

¥Parameters

没有任何。

¥None.

返回值

¥Return value

表示 str 的新字符串从其末尾(右侧)删除了空格。空白定义为 空白 个字符加 行终止符 个字符。

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

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

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

混叠

¥Aliasing

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

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

js
String.prototype.trimRight.name === "trimEnd";

示例

¥Examples

使用 trimEnd()

¥Using trimEnd()

以下示例从 str 的末尾删除空格,但不从开头删除空格。

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

js
let str = "   foo  ";

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

str = str.trimEnd();
console.log(str.length); // 6
console.log(str); // '   foo'

规范

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

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看