aboutsummaryrefslogtreecommitdiff
path: root/files/zh-cn/web/javascript/reference/global_objects/string/trim/index.html
blob: 66e0d5171f20b28013d6388b8b270f9cdb5ce934 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
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
---
<div>
<div>
<div>{{JSRef}}</div>
</div>
</div>

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

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



<h2 id="语法">语法</h2>

<pre class="syntaxbox notranslate"><code><var>str</var>.trim()</code></pre>

<h3 id="返回值">返回值</h3>

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

<h2 id="描述">描述</h2>

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

<h2 id="例子">例子</h2>

<h3 id="使用_trim">使用 <code>trim()</code></h3>

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

<pre class="brush: js notranslate">var orig = '   foo  ';
console.log(orig.trim()); // 'foo'

// 另一个 .trim() 例子,只从一边删除

var orig = 'foo    ';
console.log(orig.trim()); // 'foo'
</pre>

<h2 id="兼容旧环境">兼容旧环境</h2>

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

<pre class="brush: js notranslate">if (!String.prototype.trim) {
  String.prototype.trim = function () {
    return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
  };
}
</pre>

<h2 id="规范">规范</h2>

<table class="standard-table">
 <tbody>
  <tr>
   <th scope="col">规范</th>
   <th scope="col">状态</th>
   <th scope="col">备注</th>
  </tr>
  <tr>
   <td>{{SpecName('ES5.1', '#sec-15.5.4.20', 'String.prototype.trim')}}</td>
   <td>{{Spec2('ES5.1')}}</td>
   <td>Initial definition. Implemented in JavaScript 1.8.1.</td>
  </tr>
  <tr>
   <td>{{SpecName('ES6', '#sec-string.prototype.trim', 'String.prototype.trim')}}</td>
   <td>{{Spec2('ES6')}}</td>
   <td></td>
  </tr>
  <tr>
   <td>{{SpecName('ESDraft', '#sec-string.prototype.trim', 'String.prototype.trim')}}</td>
   <td>{{Spec2('ESDraft')}}</td>
   <td></td>
  </tr>
 </tbody>
</table>

<h2 id="浏览器兼容性">浏览器兼容性</h2>

<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p>

<p>{{Compat("javascript.builtins.String.trim")}}</p>

<h2 id="参见">参见</h2>

<ul>
 <li>{{jsxref("String.prototype.trimStart()")}}</li>
 <li>{{jsxref("String.prototype.trimEnd()")}}</li>
</ul>