String.prototype.trim()

String 值的 trim() 方法删除该字符串两端的空格并返回一个新字符串,而不修改原始字符串。

¥The trim() method of String values removes whitespace from both ends of this string and returns a new string, without modifying the original string.

要返回仅删除一端空格的新字符串,请使用 trimStart()trimEnd()

¥To return a new string with whitespace trimmed from just one end, use trimStart() or trimEnd().

Try it

语法

¥Syntax

js
trim()

参数

¥Parameters

没有任何。

¥None.

返回值

¥Return value

表示 str 的新字符串从开头和结尾删除了空格。空白定义为 空白 个字符加 行终止符 个字符。

¥A new string representing str stripped of whitespace from both its beginning and end. Whitespace is defined as white space characters plus line terminators.

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

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

示例

¥Examples

使用修剪()

¥Using trim()

以下示例删除 str 两端的空格。

¥The following example trims whitespace from both ends of str.

js
const str = "   foo  ";
console.log(str.trim()); // 'foo'

规范

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

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看