MDN 兼容旧版本写法
String.prototype.trim = function () {
return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
};
常见解法
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g, '');
}
性能较好的解法
String.prototype.trim = function() {
var str = this,
str = str.replace(/^\s+/, '');
for (var i = str.length - 1; i >= 0; i--) {
if (/\s/.test(str.charAt(i))) {
str = str.substring(0, i + 1);
break;
}
}
return str;
}