字符串去空格是常見需求,可分為去除全部空格、去除兩端空格、去除左側空格和去除右側空格。核心工具是 replace 搭配正則表達式。
str = str.replace(/\s+/g, '');
str = str.replace(/^\s+|\s+$/g, '');
str = str.replace(/^\s*/, '');
str = str.replace(/(\s*$)/g, '');
現代瀏覽器已原生支援 String.prototype.trim(),可用來去除兩端空白。若需兼容舊環境,仍可使用正則方案。