From 33058f2b292b3a581333bdfb21b8f671898c5060 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:40:17 -0500 Subject: initial commit --- .../global_objects/string/trim/index.html | 103 +++++++++++++++++++++ 1 file changed, 103 insertions(+) create mode 100644 files/zh-cn/web/javascript/reference/global_objects/string/trim/index.html (limited to 'files/zh-cn/web/javascript/reference/global_objects/string/trim') diff --git a/files/zh-cn/web/javascript/reference/global_objects/string/trim/index.html b/files/zh-cn/web/javascript/reference/global_objects/string/trim/index.html new file mode 100644 index 0000000000..66e0d5171f --- /dev/null +++ b/files/zh-cn/web/javascript/reference/global_objects/string/trim/index.html @@ -0,0 +1,103 @@ +--- +title: String.prototype.trim() +slug: Web/JavaScript/Reference/Global_Objects/String/Trim +tags: + - ECMAScript 5 + - JavaScript + - Method + - Prototype + - String + - 参考 + - 字符串 + - 方法 +translation_of: Web/JavaScript/Reference/Global_Objects/String/Trim +--- +
+
+
{{JSRef}}
+
+
+ +

trim() 方法会从一个字符串的两端删除空白字符。在这个上下文中的空白字符是所有的空白字符 (space, tab, no-break space 等) 以及所有行终止符字符(如 LF,CR等)。

+ +

{{EmbedInteractiveExample("pages/js/string-trim.html")}}

+ + + +

语法

+ +
str.trim()
+ +

返回值

+ +

一个代表调用字符串两端去掉空白的新字符串。

+ +

描述

+ +

trim() 方法返回一个从两头去掉空白字符的字符串,并不影响原字符串本身。

+ +

例子

+ +

使用 trim()

+ +

下面的例子中将显示小写的字符串 'foo':

+ +
var orig = '   foo  ';
+console.log(orig.trim()); // 'foo'
+
+// 另一个 .trim() 例子,只从一边删除
+
+var orig = 'foo    ';
+console.log(orig.trim()); // 'foo'
+
+ +

兼容旧环境

+ +

如果 trim() 不存在,可以在所有代码前执行下面代码

+ +
if (!String.prototype.trim) {
+  String.prototype.trim = function () {
+    return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
+  };
+}
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName('ES5.1', '#sec-15.5.4.20', 'String.prototype.trim')}}{{Spec2('ES5.1')}}Initial definition. Implemented in JavaScript 1.8.1.
{{SpecName('ES6', '#sec-string.prototype.trim', 'String.prototype.trim')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-string.prototype.trim', 'String.prototype.trim')}}{{Spec2('ESDraft')}}
+ +

浏览器兼容性

+ + + +

{{Compat("javascript.builtins.String.trim")}}

+ +

参见

+ + -- cgit v1.2.3-54-g00ecf