ECMAScript第五版添加了trim方法,用于去除字符串首尾的空格。

  假如让我们自己来实现的话,可以用正则表达式,也可以用常规的字符串处理方式,也可以两者混用。

  具体实现如下:

if(!String.prototype.trim){
//方法1:
String.prototype.trim = function(){
return this.replace(/^\s+/,"").replace(/\s+$/,"");
}
//方法2:
String.prototype.trim = function(){
return this.replace(/^\s+|\s+$/g,"");
}
//方法3:
String.prototype.trim = function(){
return this.replace(/^\s*([\s\S]*?)\s*$/,"$1");
}
//方法4:
String.prototype.trim = function(){
return this.replace(/^\s*([\s\S]*\S)?\s*$/,"$1");
}
//方法5:
String.prototype.trim = function(){
return this.replace(/^\s*(\S*(\s+\S+)*)\s*$/,"$1");
}
}

//方法6
if(!String.prototype.trim){
String.prototype.trim = function(){
var start = 0,
end = this.lenth -1,
workspace = "\n\r\t\f\x0b\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005" +
"\u2006\u2007\u2008\u2009\u200a\u200b\u2028\u2029\u202f\u205f\u3000\ufeff";
while(workspace.indexOf(this.charAt(start))>-1){
start++;
}
while(end>start&&workspace.indexOf(this.charAt(end))>-1){
end--;
}
return this.slice(start,end-1);

}
}


//方法7:
if(!String.prototype.trim){
String.prototype.trim = function(){
var str =this.replace(/^\s+/,""),
end = str.length-1,
ws = /\s/;
while(ws.test(str.charAt(end))){
end--;
}
return str.slice(0,end+1);

}
}



上述6个方法,性能略有不同,在选择正则表达式的时候,请结合当前字符串的情况综合考虑。