String.prototype.replace() 預設僅取代第一個匹配項。要實現全域取代,必須使用帶有 g(global)旗標的正則表達式。本文詳細說明用法與常見陷阱。
// 僅取代第一個
str.replace('搜尋字串', '取代字串');
// 全域取代:使用正則 + g 旗標
str.replace(/搜尋模式/g, '取代字串');
// 函式取代:動態計算取代內容
str.replace(/模式/g, (match, ...args) => 計算結果);
const str = '1n2n3n';
// ❌ 僅取代第一個 n
console.log(str.replace('n', ';')); // "1;2n3n"
// ✅ 全域取代所有 n
console.log(str.replace(/n/g, ';')); // "1;2;3;"
// 取代多種字元
console.log('a-b-c'.replace(/[-_]/g, ' ')); // "a b c"
// 將所有數字加 1
'價格: 10, 20, 30'.replace(/\d+/g, match => Number(match) + 1);
// "價格: 11, 21, 31"
// 交換單詞順序
'hello world'.replace(/(\w+)\s(\w+)/g, '$2 $1');
// "world hello"
// 模板字串插值
const template = '你好,{name},歡迎來到 {place}';
const data = { name: '小明', place: 'Taipei' };
const result = template.replace(/\{(\w+)\}/g, (_, key) => data[key] || '');
console.log(result); // "你好,小明,歡迎來到 Taipei"
正則模式中以下字元需逸出:\ ^ $ . | ? * + ( ) [ ] { }
// 取代字面點號
'file.name.txt'.replace(/\./g, '_'); // "file_name_txt"
// 動態建立正則需雙重逸出
function escapeRegExp(str) {
return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
const userInput = 'a.b';
new RegExp(escapeRegExp(userInput), 'g'); // /a\.b/g
'1n2n3n'.replaceAll('n', ';'); // "1;2;3;"
'hello world'.replaceAll('l', 'L'); // "heLLo worLd"
// 注意:第一參數為字串時自動全域取代,不需正則
// 若第一參數為正則,必須加 g 旗標,否則拋出 TypeError
const longStr = 'a'.repeat(100000) + 'b'.repeat(100000);
console.time('replace + regex');
longStr.replace(/a/g, 'x');
console.timeEnd('replace + regex'); // ~2-3ms
console.time('replaceAll');
longStr.replaceAll('a', 'x');
console.timeEnd('replaceAll'); // ~1-2ms(現代引擎優化)
console.time('split + join');
longStr.split('a').join('x');
console.timeEnd('split + join'); // ~3-5ms
| 錯誤代碼 | 問題 | 修正 |
|---|---|---|
str.replace('/n/g', ';') | 第一參數為字串而非正則 | str.replace(/n/g, ';') |
str.replace(/\n/g, ';') | 匹配換行符而非字母 n | str.replace(/n/g, ';') |
str.replace(new RegExp('*'), 'x') | * 為特殊字元需逸出 | str.replace(/\*/g, 'x') |
str.replace(/pattern/, fn) | 無 g 旗標,函式僅執行一次 | str.replace(/pattern/g, fn) |
replaceAll()(ES2021+)/pattern/g 正則escapeRegExp 防止注入