字串去除空白是表單驗證、資料清洗的高頻需求。ES5 引入 String.prototype.trim() 解決首尾空白,但「去除所有空白」、「僅去首/尾」仍需正則。本文整理各種去空白需求的標準寫法與相容性處理。
const str = ' Hello World ';
str.trim(); // "Hello World" - 去除首尾空白(含換行、Tab)
str.trimStart(); // "Hello World " - ES2019,去除開頭空白
str.trimEnd(); // " Hello World" - ES2019,去除結尾空白
str.trimLeft(); // 非標準別名,等同 trimStart()
str.trimRight(); // 非標準別名,等同 trimEnd()
| 需求 | 正則 | 範例結果 |
|---|---|---|
| 去除所有空白(含空格、Tab、換行) | /\s+/g | ' a b\tc\n'.replace(/\s+/g, '') // 'abc' |
| 僅去除空格字元(保留 Tab、換行) | / /g 或 /[ ]/g | ' a b\tc'.replace(/ /g, '') // 'ab\tc' |
| 去除首尾空白(等同 trim) | /^\s+|\s+$/g | ' abc '.replace(/^\s+|\s+$/g, '') // 'abc' |
| 去除開頭空白 | /^\s+/ | ' abc'.replace(/^\s+/, '') // 'abc' |
| 去除結尾空白 | /\s+$/ | 'abc '.replace(/\s+$/, '') // 'abc' |
| 合併連續空白為單一空格 | /\s+/g 替換為 ' ' | 'a b\tc'.replace(/\s+/g, ' ') // 'a b c' |
if (!String.prototype.trim) {
String.prototype.trim = function() {
return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
};
}
// 若需支援 trimStart/trimEnd
if (!String.prototype.trimStart) {
String.prototype.trimStart = function() {
return this.replace(/^[\s\uFEFF\xA0]+/, '');
};
}
if (!String.prototype.trimEnd) {
String.prototype.trimEnd = function() {
return this.replace(/[\s\uFEFF\xA0]+$/, '');
};
}
注意:\uFEFF (BOM)、\xA0 (NBSP) 為常見不可見空白字元,建議納入 Polyfill。
const StrUtil = {
// 去除首尾空白
trim(str) {
return (str || '').trim();
},
// 去除所有空白(含換行、Tab)
trimAll(str) {
return (str || '').replace(/\s+/g, '');
},
// 僅去除空格字元
trimSpaces(str) {
return (str || '').replace(/ /g, '');
},
// 合併連續空白為單一空格
normalize(str) {
return (str || '').replace(/\s+/g, ' ').trim();
},
// 表單輸入即時清理:綁定 input/blur 事件
bindAutoTrim(inputEl, options = {}) {
const { all = false, normalize = false } = options;
const clean = all ? this.trimAll : (normalize ? this.normalize : this.trim);
['input', 'blur'].forEach(evt => {
inputEl.addEventListener(evt, () => { inputEl.value = clean(inputEl.value); });
});
}
};
// 使用範例
StrUtil.bindAutoTrim(document.getElementById('username'), { normalize: true });
StrUtil.bindAutoTrim(document.getElementById('password'), { all: true });
const TRIM_ALL = /\s+/g; 重複使用。\s 匹配範圍較廣:包含 [\t\n\v\f\r \u00A0\u2000-\u200A\uFEFF],若只想去「空格」請用 / /g。split(' ').join('') 在某些引擎比 replace(/ /g, '') 更快,可自行 Benchmark。form.submit 事件中遍歷所有輸入框呼叫 trim(),避免後端再處理。現代專案直接使用 trim()/trimStart()/trimEnd() 處理首尾空白;去除所有空白用 replace(/\s+/g, '');需支援 IE8 時加載 Polyfill。封裝通用工具函式可統一專案風格並減少 Bug。