- 方法一
str.replace(/\ +/g, ""); // 去除 空格
str.replace(/[\r\n]/g, ""); // 去除 换行符
str.trim(); // 去除 前后空格
正则去除所有空格
str.replace(/\s*/g,"")
- 方法二
//
function trim(str){
return (str || "").replace(/^\s+|\s+$/g,"");
}
- 方法三
// 利用slice 去除尾部空格
function trim(str){
var str = str.replace(/^\s\s*/, ''),
ws = /\s/,
i = str.length;
while (ws.test(str.charAt(--i)));
return str.slice(0, i + 1);
}