trim()
方法会从一个字符串的两端删除空白字符。在这个上下文中的空白字符是所有的空白字符 (space, tab, no-break space 等) 以及所有行终止符字符(如 LF,CR等)。
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
语法
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, ''); }; }
规范
规范 | 状态 | 备注 |
---|---|---|
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 |
浏览器兼容性
The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.
Update compatibility data on GitHub
Desktop | Mobile | Server | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
trim |
Chrome Full support 4 | Edge Full support 12 | Firefox Full support 3.5 | IE Full support 9 | Opera Full support 10.5 | Safari Full support 5 | WebView Android Full support ≤37 | Chrome Android Full support 18 | Firefox Android Full support 4 | Opera Android Full support 11 | Safari iOS Full support Yes | Samsung Internet Android Full support 1.0 | nodejs Full support Yes |
Legend
- Full support
- Full support