第一种:循环去除
function trim(str){
var copy,whiteSpace=new String(" \t\r\n");
if((copy=str)=='') return '';
while(true){
if(whiteSpace.indexOf(copy.charAt(0))!=-1) copy=copy.substring(1,parseInt(copy.length));
else if(parseInt(copy.length)!=0&&whiteSpace.indexOf(copy.charAt(parseInt(copy.length)-1))!=-1) copy=copy.substring(0,parseInt(copy.length)-1);
else return copy;
}
}
第二种:匹配正则
function trim(str){
var copy=str.replace(/(^\s+)|(\s+&)/g,'');
return copy;
}