js去掉字符串前后空格三种方法及最佳方案

第一种:非正则表达式循环检索--在长的头尾空格字符串中使用效率较低

 1 if(!String.prototype.trim){
 2   String.prototype.trim = function(){
 3         var start = 0,
 4             end = this.length - 1,
 5             //包括ECMAScript5中定义的所有空白字符
 6             ws = "\n\r\t\f\x0b\xa0\u1680\u180e
 7             \u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009
 8             \u200a\u200b\u2028\u2029\u202f\u205f\u3000\ufeff";
 9         while(ws.indexOf(this.charAt(start))>-1){
10             start++;
11         }
12         while(end>start && ws.indexOf(this.charAt(end))>-1){
13             end--;
14         }
15         return this.slice(start,end+1);
16     }
17 }

 第二种:利用正则表达式--在去除尾空格时效率比较低

1 if(!String.prototype.trim){
2     String.prototype.trim = function() 
3     { 
4         return this.replace(/^\s+/,"").replace(/\s+$/,"");
5     }
6 }

第三种:最佳方法:用正则表达式除去头部空格,用非正则表达式去除尾部空格

 1 if(!String.prototype.trim){
 2   String.prototype.trim = function(){
 3         var str = this.replace(/^\s+/,""),
 4             end = this.length - 1,
 5             ws = /\s/;
 6             while(ws.test(this.charAt(end))){
 7                 end--;
 8             }
 9             return this.slice(0,end+1);
10     }
11 }
posted @ 2012-06-14 12:20  无赖君子  阅读(2508)  评论(4编辑  收藏  举报