萬盛學電腦網

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

JavaScript String.prototype.replace() 進階用法全解析:正則標誌、函數替換、分組引用、常見陷阱

String.prototype.replace() 是 JS 字符串處理最核心的方法,掌握其**正則標誌、替換函數、分組引用、特殊替換模式**能解決 90% 文本轉換需求。本文系統講解進階用法並列舉常見坑點。

基礎語法回顧

str.replace(regexp|substr, newSubstr|function)
// 返回新字符串,原字符串不變
// 不加全局標誌 g 時,僅替換第一個匹配

核心進階技巧

1. 正則標誌組合

標誌含義示例
g全局匹配 (所有)"a a a".replace(/a/g, "b") // "b b b"
i忽略大小寫"AbC".replace(/a/i, "X") // "XbC"
m多行模式 (^$ 匹配行首尾)"a\nb".replace(/^/gm, ">") // ">a\n>b"
s (ES2018)dotAll: . 匹配換行符"a\nb".replace(/a.b/s, "X") // "X"
u (ES2015)Unicode 模式 (正確處理代理對)"😀".replace(/./u, "X") // "X"
y (ES2015)粘連匹配 (從 lastIndex 開始)配合 exec 解析器使用

2. 替換函數 (Function Replacer) — 最強大特性

第二個參數為函數時,每次匹配調用,返回值作為替換文本。參數:(match, p1, p2, ..., offset, string)。

// 駝峰轉下劃線
"helloWorld".replace(/([A-Z])/g, function(m, p1) { return '_' + p1.toLowerCase(); }); // "hello_world"

// 模板引擎簡易實現
var tpl = "Hello, {{name}}! You have {{count}} messages.";
var data = {name: "Jack", count: 5};
var result = tpl.replace(/\{\{(\w+)\}\}/g, function(_, key) { return data[key] || ''; });
// "Hello, Jack! You have 5 messages."

// 動態計算替換
"price: $10, $20, $5".replace(/\$(\d+)/g, function(m, p1) {
    return '$' + (parseInt(p1) * 1.1).toFixed(2); // 加 10% 稅
}); // "price: $11.00, $22.00, $5.50"

3. 字符串替換中的特殊變量 (僅字符串替換模式生效)

模式含義
$$插入 "$"
$&匹配的整個子串
$`匹配之前的文本
$'匹配之後的文本
$n第 n 個分組捕獲 (n=1..99)
$<Name> (ES2018)具名分組捕獲
"2023-05-20".replace(/(\d{4})-(\d{2})-(\d{2})/, '$2/$3/$1'); // "05/20/2023"
"abc".replace('b', '$`$&$\\''); // "a" + "b" + "c" = "abc" (演示上下文引用)

4. 常見陷阱與避坑

陷阱現象解決
字符串參數不支援全局"a a a".replace("a", "b") // "b a a" 只替換第一個必須用正則 /a/g
正則未加 g 但預期全局同理,只替換首個加 g 標誌
特殊字符未轉義"1.5".replace(".", ",") // "1,5" 但 ". " 是正則元字符匹配任意字符用 escapeRegExp 或 new RegExp(escape(str), 'g')
替換函數中 this 指向非嚴格模式指向全局對象,嚴格模式 undefined用箭頭函數或 bind,不依賴 this
replaceAll (ES2021) 字符串參數"a a a".replaceAll("a", "b") // "b b b" 直接全局推薦簡單全局替換用 replaceAll

實戰工具函數庫

const StrUtil = {
    // 轉義正則特殊字符
    escapeRegExp: s => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'),
    
    // 全局替換字符串 (無需正則)
    replaceAll: (str, search, replacement) => 
        str.split(StrUtil.escapeRegExp(search)).join(replacement),
    
    // 模板渲染 {{key}} / {{key|filter}}
    template: (tpl, data) => tpl.replace(/\{\{(\w+)(?:\|(\w+))?\}\}/g, (_, key, filter) => {
        var val = data[key];
        if (filter && StrUtil.filters[filter]) val = StrUtil.filters[filter](val);
        return val != null ? val : '';
    }),
    filters: {
        upper: s => String(s).toUpperCase(),
        lower: s => String(s).toLowerCase(),
        json: s => JSON.stringify(s)
    },
    
    // 駝峰 ↔ 下劃線
    toCamel: s => s.replace(/[-_](\w)/g, (_, c) => c.toUpperCase()),
    toSnake: s => s.replace(/([A-Z])/g, '_$1').toLowerCase().replace(/^_/, ''),
    
    // 高亮關鍵字
    highlight: (text, keyword, tag = 'mark') => 
        keyword ? text.replace(new RegExp('(' + StrUtil.escapeRegExp(keyword) + ')', 'gi'), '<' + tag + '>$1') : text
};

性能提示

  • 大量重複替換:預編譯 const regex = /pattern/g 避免重複創建 RegExp 對象。
  • 超長字符串 (MB 級):考慮 String.prototype.replaceAll (原生優化) 或流式處理。
  • 避免在循環中動態構造正則:new RegExp(var) 每次都編譯,極慢。

精通 replace 進階用法,能用極少代碼解決複雜文本轉換、模板渲染、數據清洗等高頻問題,是 JS 基礎功的重要體現。

copyright © 萬盛學電腦網 all rights reserved