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 2017 Draft (ECMA-262) String.prototype.trim |
Draft |
浏览器兼容性
| 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 | ? | ? | ? | ? | ? |