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

## 语法

    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, '');
      };
    }

## 规范

Specification | Status | Comment
--- | --- | ---
ECMAScript 5.1 (ECMA-262) String.prototype.trim | Standard | Initial definition. Implemented in JavaScript 1.8.1.
ECMAScript 2015 (6th Edition, ECMA-262) String.prototype.trim | Standard |
ECMAScript Latest Draft (ECMA-262) String.prototype.trim | Draft |

## 浏览器兼容性

We're converting our compatibility data into a machine-readable JSON format. This compatibility table still uses the old format, because we haven't yet converted the data it contains. Find out how you can help!

- Desktop
- Mobile

Feature | Firefox (Gecko) | Chrome | Internet Explorer | Opera | Safari
--- | --- | --- | --- | --- | ---
Basic support | 3.5 (1.9.1) | (Yes) | 9 | 10.5 | 5

Feature | Firefox Mobile (Gecko) | Android | IE Mobile | Opera Mobile | Safari Mobile
--- | --- | --- | --- | --- | ---
Basic support | ? | ? | ? | ? | ?

## 相关链接

- `String.prototype.trimLeft()`
- `String.prototype.trimRight()`