js 去除字符串中的空格

正则 replace 方法

  • 去除字符串所有空格:
str.replace(/s*/g, '');
  • 去除字符串两头的空格
str.replace(/^s*|s*$/g, '');
  • 去除字符串头部空格:
str.replace(/^s*/g, '');
  • 去除字符串尾部空格:
str.replace(/s*$/g, '');

trim()

trim() 方法只能删除字符串两侧代码

str.trim();

ES6

let str = '  a  b c  ';
let arr = Array.from(new Set(str.split(''))).filter(val => val && val.trim());
str = arr.join('');
原文地址:https://www.cnblogs.com/cckui/p/11506786.html