String.prototype.replace() 是 JS 字符串處理最核心的方法,掌握其**正則標誌、替換函數、分組引用、特殊替換模式**能解決 90% 文本轉換需求。本文系統講解進階用法並列舉常見坑點。
str.replace(regexp|substr, newSubstr|function)
// 返回新字符串,原字符串不變
// 不加全局標誌 g 時,僅替換第一個匹配
| 標誌 | 含義 | 示例 |
|---|---|---|
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 解析器使用 |
第二個參數為函數時,每次匹配調用,返回值作為替換文本。參數:(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"
| 模式 | 含義 |
|---|---|
$$ | 插入 "$" |
$& | 匹配的整個子串 |
$` | 匹配之前的文本 |
$' | 匹配之後的文本 |
$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" (演示上下文引用)
| 陷阱 | 現象 | 解決 |
|---|---|---|
| 字符串參數不支援全局 | "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' + tag + '>') : text
};
const regex = /pattern/g 避免重複創建 RegExp 對象。String.prototype.replaceAll (原生優化) 或流式處理。new RegExp(var) 每次都編譯,極慢。精通 replace 進階用法,能用極少代碼解決複雜文本轉換、模板渲染、數據清洗等高頻問題,是 JS 基礎功的重要體現。