DIV CSS 佈局教程網

用 replace 替換字串內容:從單次取代到全量取代
編輯:關於JavaScript     

replace 是字串替換的基本工具。以下範例把段落中的 "Microsoft" 換成 "jb51.net",點擊按鈕後立即生效:

<!DOCTYPE html>
<html>
<body>
<p>Click the button to replace "Microsoft" with "jb51.net" in the paragraph below:</p>
<p id="demo">Visit Microsoft!</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
  var str = document.getElementById("demo").innerHTML;
  var n = str.replace("Microsoft", "jb51.net");
  document.getElementById("demo").innerHTML = n;
}
</script>
</body>
</html>

最容易踩的坑:只換第一個

當第一個參數是字串時,replace 只會替換第一個比對到的片段:

"a-b-c".replace("-", "+");    // "a+b-c" —— 只換一處

要全部替換,過去必須用帶 g 旗標的正則:

"a-b-c".replace(/-/g, "+");   // "a+b+c"

ES2021 之後有了更清楚的寫法:

"a-b-c".replaceAll("-", "+"); // "a+b+c"

善用取代函式

第二個參數可以傳函式,讓你依「比對到的內容」決定要換成什麼,這是做動態替換的關鍵:

// 把 $1 $2 換成實際的群組內容
"2024-01-15".replace(/(\d{4})-(\d{2})-(\d{2})/, "$2/$3/$1"); // "01/15/2024"

// 用函式做依內容而定的替換
"1,234,567".replace(/\B(?=(\d{3})+(?!\d))/g, ",");           // 千分位

// 捕獲群組搭配 arrow function
"John Smith".replace(/(\w+)\s(\w+)/, (m, first, last) => last + ", " + first);
// "Smith, John"

另外要留意:替換字串中的 $ 有特別意義($& 代表比對到的整段、$' 代表比對位置之後的內容等)。若你要插入的字面內容剛好含 $,請改用函式形式回傳,就不會被解析。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved