萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 字串去除空白字元完整速查表

前言

字串去除空白是資料清洗、表單驗證、API 參數處理的高頻操作。本文系統整理 JS 原生方法、正則表達式、ES2019 新增方法、以及效能比較,提供可直接複製使用的工具函式庫。

ES2019 標準方法 (現代首選,無需正則)

方法說明範例支援度
trim() 移除首尾空白 (含換行、Tab、全形空白等 Unicode 空白) ' hello '.trim() // 'hello' ES2019 / 全瀏覽器
trimStart() / trimLeft() 僅移除開頭空白 ' hello '.trimStart() // 'hello ' ES2019 / 全現代瀏覽器
trimEnd() / trimRight() 僅移除結尾空白 ' hello '.trimEnd() // ' hello' ES2019 / 全現代瀏覽器

trimLeft/trimRight 為別名,標準建議使用 trimStart/trimEnd。

正則表達式方案 (舊環境相容 / 複雜需求)

常用正則模式

const str = '  \t\n  Hello World  \n\r  ';

// 1. 移除首尾空白 (等同 trim)
str.replace(/^\s+|\s+$/g, '');           // 'Hello World'
str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, ''); // 含 BOM、NBSP

// 2. 移除所有空白 (含中間)
str.replace(/\s+/g, '');                 // 'HelloWorld'

// 3. 僅移除開頭空白
str.replace(/^\s+/, '');                 // 'Hello World  \n\r  '

// 4. 僅移除結尾空白
str.replace(/\s+$/, '');                 // '  \t\n  Hello World'

// 5. 合併多個連續空白為單一空白 (保留單字間隔)
str.replace(/\s+/g, ' ').trim();         // 'Hello World'

// 6. 移除特定字元 (如全形空白 \u3000、零寬空白 \u200B)
str.replace(/[\u3000\u200B]/g, '');

正則字元類別速查

  • \s:[ \t\n\r\f\v] (空格、Tab、換行、換頁、垂直定位)
  • \uFEFF:BOM (Byte Order Mark)
  • \u00A0 /  :不換行空白 (NBSP)
  • \u3000:全形空白 (中文常見)
  • \u200B:零寬空白 (Zero Width Space)

效能比較測試 (100萬次迴圈)


const testStr = '  \t\n  Hello World  \n\r  '.repeat(100);

console.time('trim()');
for(let i=0;i<1e6;i++) testStr.trim();
console.timeEnd('trim()'); 
// trim(): ~45ms (原生優化極佳)

console.time('replace /^\\s+|\\s+$/g');
for(let i=0;i<1e6;i++) testStr.replace(/^\s+|\s+$/g, '');
console.timeEnd('replace'); 
// replace: ~120ms

console.time('replace /\\s+/g');
for(let i=0;i<1e6;i++) testStr.replace(/\s+/g, '');
console.timeEnd('replace all'); 
// replace all: ~180ms

結論:簡單首尾去空白**永遠優先使用 trim()**,原生實作為 C++ 優化,快 2-3 倍。

實用工具函式庫 (可直接複製)


const StrUtil = {
    // 基礎去空白
    trim: s => s?.trim() ?? '',
    trimStart: s => s?.trimStart() ?? '',
    trimEnd: s => s?.trimEnd() ?? '',

    // 移除所有空白 (含中間)
    trimAll: s => s?.replace(/\s+/g, '') ?? '',

    // 正規化空白:合併連續空白為單一空白 + 首尾去空白
    normalize: s => s?.replace(/\s+/g, ' ').trim() ?? '',

    // 移除中文全形空白、零寬空白、BOM 等隱形字元
    cleanInvisible: s => s?.replace(/[\uFEFF\u00A0\u3000\u200B-\u200F\uFEFF]/g, '') ?? '',

    // 表單輸入標準化:去首尾 + 合併中間空白 + 清理隱形字元
    sanitizeInput: s => StrUtil.normalize(StrUtil.cleanInvisible(s)),

    // 檢查是否為空白字串 (含只含空白)
    isBlank: s => !s || /^\s*$/.test(s),

    // 取得非空白字元長度
    visibleLength: s => (s || '').replace(/\s/g, '').length
};

// 使用範例
const dirty = '  \u3000\u200B  用戶 輸入  \n\t  ';
console.log(StrUtil.sanitizeInput(dirty)); // '用戶 輸入'
console.log(StrUtil.isBlank('   \n\t  ')); // true

表單驗證實戰應用


function validateForm(formData) {
    const errors = {};
    
    // 姓名:去首尾空白,不可為空,長度 2-20
    const name = StrUtil.trim(formData.name);
    if (StrUtil.isBlank(name)) errors.name = '姓名不可為空';
    else if (name.length < 2 || name.length > 20) errors.name = '姓名長度 2-20 字';
    
    // 手機:移除所有空白後驗證格式
    const phone = StrUtil.trimAll(formData.phone);
    if (!/^09\d{8}$/.test(phone)) errors.phone = '手機格式錯誤';
    
    // 內容:正規化空白,最少 10 字
    const content = StrUtil.normalize(formData.content);
    if (content.length < 10) errors.content = '內容至少 10 字';
    
    return { isValid: Object.keys(errors).length === 0, errors, sanitized: { name, phone, content } };
}

常見陷阱與避坑指南

陷阱錯誤代碼正確做法
\s 不匹配全形空白 ' '.replace(/\s/g, '') // 仍為 ' ' 加入 \u3000:/[\s\u3000]/g
^/\s+$/ 只匹配全空白字串 ' a '.replace(/^\s+$/, '') // 無效果 用 /^\s+|\s+$/g (首尾分別匹配)
replace 不修改原字串 str.replace(/\s/g, ''); console.log(str); // 未變 字串不可變,必須接收回傳值:str = str.replace(...)
密碼欄位誤用 trim() 使用者故意設定前後空白作為密碼一部分 密碼欄位**不應**自動 trim,尊重使用者輸入

總結建議

  1. 首選 trim()/trimStart()/trimEnd():原生、快速、語意清晰、支援完整 Unicode 空白
  2. 移除所有空白:str.replace(/\s+/g, '')
  3. 表單輸入正規化:封裝 sanitizeInput 統一處理 (去首尾、合併中間、清理隱形字元)
  4. 密碼/驗證碼欄位:嚴禁自動 trim,保留使用者原始輸入
  5. 效能敏感場景:避免在熱路徑大量使用正則,優先用原生方法
copyright © 萬盛學電腦網 all rights reserved