萬盛學電腦網

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

JavaScript String.prototype.replace() 完整指南:字串替換與進階模式

前言

replace() 依正則或子字串搜尋並替換,回傳新字串(原字串不變)。支援函式回呼、特殊替換模式($&, $`, $', $n, $$),是字串處理的瑞士刀。

語法

str.replace(regexp|substr, newSubStr|function)

參數說明

  • regexp:RegExp 物件(若有 g 則全域替換)。
  • substr:字串,僅替換第一個匹配。
  • newSubStr:替換字串,可包含特殊模式。
  • function:回呼函式,參數 (match, group1, ..., offset, string),回傳替換字串。

特殊替換模式

$n ($1~$99)$<Name>
模式意義
$$插入 "$"
$&插入完整匹配字串
$`插入匹配前的字串
$'插入匹配後的字串
插入第 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>

replaceAll() (ES2021)

'a-b-c'.replaceAll('-', '_'); // 'a_b_c'
// 等同於 .replace(/-/g, '_') 但語意更清晰,且第一參數為字串時不需轉 RegExp

總結

replace() 配合函式回呼與特殊模式,能處理極複雜的字串轉換。記住:字串不可變,必須接收回傳值;全域替換請用 g 旗標或 replaceAll()。

copyright © 萬盛學電腦網 all rights reserved