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 |
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 | ? | ? | ? | ? | ? |