| 需求 | 正則表達式 | 說明 |
|---|---|---|
| 移除所有空格 | /\s+/g | \s 匹配空白字符(空格、制表、換行) |
| 移除中文字符 | /[\u4e00-\u9fa5]/g | 基本多文種平面中文範圍 |
| 移除中文+標點 | /[\u4e00-\u9fa5\u3000-\u303f\uff00-\uffef]/g | 含全角標點、符號 |
| 去首尾空白 | /^\s+|\s+$/g | 或用 `str.trim()` (ES5+) |
// 1. 移除所有空格
function removeSpaces(str) {
return str.replace(/\s+/g, '');
}
// 2. 移除中文字符(保留字母數字符號)
function removeChinese(str) {
return str.replace(/[\u4e00-\u9fa5]/g, '');
}
// 3. 移除中文、空格、常見標點(獲取純字母數字)
function keepAlphanumeric(str) {
return str.replace(/[^\w\d]/g, ''); // \w 包含字母數字下劃線
}
// 4. 原型擴展(慎用,污染原型)
String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ''); };
String.prototype.ltrim = function() { return this.replace(/^\s+/g, ''); };
String.prototype.rtrim = function() { return this.replace(/\s+$/g, ''); };
String.prototype.removeSpaces = function() { return this.replace(/\s+/g, ''); };
String.prototype.removeChinese = function() { return this.replace(/[\u4e00-\u9fa5]/g, ''); };
// 使用
" abc def ".trim(); // "abc def"
" abc ".removeSpaces(); // "abc"
"字符串123".removeChinese(); // "123"
function cleanInput(str) {
return String(str) // 確保字符串
.replace(/[\u4e00-\u9fa5]/g, '') // 移除中文
.replace(/\s+/g, '') // 移除空白
.replace(/[^\w\-_.]/g, ''); // 只保留字母數字下劃線中劃線點
}
基本多文種平面 (BMP) 之外的罕見字符(如 Emoji 😀 U+1F600)不在 `\u4e00-\u9fa5` 範圍。需移除所有「字母類」字符時,可用 Unicode 屬性逃逸(ES2018+):`str.replace(/\p{Script=Han}/gu, '')` 移除所有漢字,`/\p{L}/gu` 移除所有字母。舊環境需引入 polyfill。