js原生方法trim()
str = str.trim();
局限:只能去除字符串两边空格
let str = " 1 2 3 ";
str0 = str.trim();
// "1 2 3"
正则表达式
去除字符串所有空格
str = str.replace(/\s*/g,"");
去除字符串两边空格
str = str.replace(/^\s*|\s*$/g,"");
去除字符串左侧空格
str = str.replace(/^\s*/g,"");
去除字符串右侧空格
str = str.replace(/\s*$/g,"");
str1 = str.replace(/\s*/g,"");
// "123"
str2 = str.replace(/^\s*|\s*$/g,"");
// "1 2 3"
str3 = str.replace(/^\s*/g,"");
// "1 2 3 "
str4 = str.replace(/\s*$/g,"");
// " 1 2 3"
参考