replace 基礎語法
str.replace(regexp|substr, newSubstr|function)
常見用法範例
1. 替換首次出現 (字串參數)
'The cat'.replace('The', 'A'); // "A cat"
2. 替換所有 (全域正則)
'The The The'.replace(/The/g, 'A'); // "A A A"
3. 使用特殊替換符號
'2024-01-01'.replace(/(\d{4})-(\d{2})-(\d{2})/, '$2/$3/$1'); // "01/01/2024"
'foo bar'.replace(/(\w+)\s(\w+)/, '$2 $1'); // "bar foo" (交換單詞)
4. 函式替換 (動態計算)
'32F 212F'.replace(/(\d+(?:\.\d*)?)F/g, (_, n) => ((n-32)*5/9).toFixed(1)+'C'); // "0.0C 100.0C"
模擬 replaceAll (舊環境相容)
String.prototype.replaceAll = function (search, replace) {
return this.replace(new RegExp(search.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'g'), replace);
};
// 使用
'abcabcabc'.replaceAll('a', 'x'); // "xbcxbcxbc"
現代標準:String.prototype.replaceAll (ES2021)
'abcabcabc'.replaceAll('a', 'x'); // 直接可用,無需正則轉義
效能提示
- 大量替換優先用正則
/g,避免迴圈
- 固定字串替換用
split/join 更快:str.split('a').join('x')