replace() 依正則或子字串搜尋並替換,回傳新字串(原字串不變)。支援函式回呼、特殊替換模式($&, $`, $', $n, $$),是字串處理的瑞士刀。
str.replace(regexp|substr, newSubStr|function)
g 則全域替換)。(match, group1, ..., offset, string),回傳替換字串。| 模式 | 意義 |
|---|---|
$$ | 插入 "$" |
$& | 插入完整匹配字串 |
$` | 插入匹配前的字串 |
$' | 插入匹配後的字串 |
| 插入第 n 個捕獲群組 | |
| 具名捕獲群組 (ES2018) |
<script>
// 全域忽略大小寫替換
const re = /apples/gi;
const str = 'Apples are round, and apples are juicy.';
console.log(str.replace(re, 'oranges'));
// "oranges are round, and oranges are juicy."
// 交換單詞順序(使用群組引用)
const re2 = /(\w+)\s(\w+)/;
console.log('zara ali'.replace(re2, '$2, $1')); // "ali, zara"
</script>
<script>
// 將所有數字乘 2
'price: 10, qty: 5'.replace(/\d+/g, m => Number(m) * 2);
// "price: 20, qty: 10"
// 具名群組替換 (ES2018)
const re = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/;
'2024-12-25'.replace(re, '$<month>/$<day>/$<year>');
// "12/25/2024"
// 避免 XSS:HTML 轉義
function escapeHtml(str) {
return str.replace(/[&<>"']/g, m => ({
'&': '&', '<': '<', '>': '>', '"': '"', "'": '''
})[m]);
}
</script>
'a-b-c'.replaceAll('-', '_'); // 'a_b_c'
// 等同於 .replace(/-/g, '_') 但語意更清晰,且第一參數為字串時不需轉 RegExp
replace() 配合函式回呼與特殊模式,能處理極複雜的字串轉換。記住:字串不可變,必須接收回傳值;全域替換請用 g 旗標或 replaceAll()。