最簡潔有效的方式是使用 `String.prototype.replace` 搭配全域正則:
// 移除所有空白字元(空格、Tab、換行、回車等)
str = str.replace(/\s/g, '');
// 僅移除首尾空白(保留中間空格)
str = str.trim(); // ES5+ 瀏覽器支援
// 移除首尾並合併中間多重空白為單一空格
str = str.trim().replace(/\s+/g, ' ');
// 假設已取得某行文字
let line = " 這是一行 含有 多餘空格 的文字 \n";
line = line.replace(/\s/g, ''); // 結果: "這是一行含有多餘空格的文字"
input.addEventListener('input', function() {
// 僅允許可見字元,移除所有控制字元
this.value = this.value.replace(/[\x00-\x1F\x7F]/g, '');
});
| 模式 | 匹配內容 |
|---|---|
| `\s` | 所有空白字元:空格、Tab(`\t`)、換行(`\n`)、回車(`\r`)、分頁(`\f`) |
| `\s+` | 連續一個以上空白字元 |
| `^\s+|\s+$` | 字串首尾空白 |
忘記加 `g` 旗標(全域匹配),導致僅替換第一個匹配項:
// 錯誤
str.replace(/\s/, ''); // 只移除第一個空白
// 正確
str.replace(/\s/g, ''); // 移除所有空白