JavaScript replace() 方法完整教學:從基礎到正規表達式與實用技巧

1. 前言

JavaScript 是網頁開發中最廣泛使用的程式語言之一。特別是,字串操作在處理使用者輸入或資料時經常會用到。其中,replace() 方法被認為是一個能夠輕鬆進行字串替換的強大工具。 本文將從基礎到進階,詳細解說 JavaScript 的 replace() 方法。不僅包含基本用法,還會介紹利用正規表達式的高階替換與實務範例,適合初學者到中級開發者。

2. replace() 方法的基礎

什麼是 replace() 方法?

replace() 方法是 JavaScript 內建的函式,用來將字串中的特定部分替換成另一個字串。透過此方法,可以有效率地編輯與轉換字串資料。

語法

string.replace(pattern, replacement)
  • pattern: 要搜尋的字串或正規表達式。
  • replacement: 要替換的字串,或回呼函式。

基本用法

以下範例示範簡單的字串替換:
let text = "Hello, world!";
let result = text.replace("world", "JavaScript");
console.log(result); // "Hello, JavaScript!"
這段程式碼將「world」字串替換成「JavaScript」。

注意事項

  1. replace() 只會替換第一個符合的結果。
  2. 若要替換所有符合的字串,需要搭配正規表達式與 g 標誌。

3. 使用正規表達式的進階替換

什麼是正規表達式?

正規表達式是一種用來表示字串模式的強大工具。在 JavaScript 中,可以透過正規表達式輕鬆完成複雜的搜尋與替換。

正規表達式替換範例

let text = "apple, banana, apple";
let result = text.replace(/apple/g, "orange");
console.log(result); // "orange, banana, orange"

常見標誌

  • g: 全域替換(替換所有符合的結果)
  • i: 忽略大小寫
  • m: 多行模式

應用範例:忽略大小寫替換

let text = "Hello, hello, HELLO";
let result = text.replace(/hello/gi, "hi");
console.log(result); // "hi, hi, hi"

4. 多處替換

全域替換

若要替換多個符合的字串,可以使用正規表達式的 g 標誌。
let text = "cat dog cat bird";
let result = text.replace(/cat/g, "fish");
console.log(result); // "fish dog fish bird"

一次替換多個不同字串的技巧

let text = "red blue green";
let replacements = {red: "pink", blue: "cyan", green: "lime"};

Object.keys(replacements).forEach(key => {
  let regex = new RegExp(key, "g");
  text = text.replace(regex, replacements[key]);
});

console.log(text); // "pink cyan lime"
這種方法可以一次替換多個模式,並提升程式碼的可讀性。

5. 使用回呼函式進行動態替換

什麼是回呼函式?

回呼函式是在替換過程中被呼叫的函式,能夠利用目前的匹配資訊來客製化處理。

動態替換範例

1. 交換字串順序

let text = "Tanaka, Taro";
let result = text.replace(/(w+), (w+)/, (match, p1, p2) => {
  return `${p2} ${p1}`;
});
console.log(result); // "Taro Tanaka"

2. 日期格式轉換

let date = "2024-12-25";
let formattedDate = date.replace(/(d{4})-(d{2})-(d{2})/, (match, year, month, day) => {
  return `${month}/${day}/${year}`;
});
console.log(formattedDate); // "12/25/2024"

6. 特殊字元與跳脫序列的處理

什麼是特殊字元?

在正規表達式中,某些字元是特殊符號(meta character),具有特別的意義。若要直接搜尋或替換這些字元,必須使用跳脫序列

替換包含特殊字元的字串

範例1: 替換包含句點的字串

let text = "www.example.com";
let result = text.replace(/./g, "-");
console.log(result); // "www-example-com"

範例2: 移除美元符號

let price = "$1,000";
let result = price.replace(/$/g, "");
console.log(result); // "1,000"

HTML 跳脫字元替換

範例: HTML 標籤跳脫

let html = "<div>Hello!</div>";
let result = html.replace(/</g, "&lt;").replace(/>/g, "&gt;");
console.log(result);
// "&lt;div&gt;Hello!&lt;/div&gt;"

7. 實務範例與應用技巧

將換行符號轉換成 <br> 標籤

let text = "HellonWorldnJavaScript";
let result = text.replace(/n/g, "<br>");
console.log(result);
// "Hello<br>World<br>JavaScript"

操作 URL 參數

let url = "https://example.com/?id=123&lang=en";
let result = url.replace(/lang=en/, "lang=ja");
console.log(result);
// "https://example.com/?id=123&lang=ja"

使用者輸入的淨化處理

function sanitizeInput(input) {
  return input.replace(/</g, "&lt;").replace(/>/g, "&gt;");
}

let userInput = "<script>alert('XSS');</script>";
let safeInput = sanitizeInput(userInput);
console.log(safeInput);
// "&lt;script&gt;alert('XSS');&lt;/script&gt;"

8. 注意事項與最佳實踐

僅會替換第一個符合項目

let text = "apple apple orange";
let result = text.replace("apple", "banana");
console.log(result); // "banana apple orange"

注意大小寫區分

let text = "JavaScript is powerful. javascript is versatile.";
let result = text.replace(/javascript/gi, "JS");
console.log(result);
// "JS is powerful. JS is versatile."

注意特殊字元的跳脫

function escapeRegExp(str) {
  return str.replace(/[.*+?^${}()|[]\]/g, "\$&");
}

let text = "Price: $100";
let result = text.replace(new RegExp(escapeRegExp("$"), "g"), "USD ");
console.log(result);
// "Price: USD 100"

9. 總結

文章回顧

  • 基礎用法: 說明了 replace() 方法的語法與基本替換範例。
  • 正規表達式應用: 學習了如何透過正規表達式與標誌進行進階替換。
  • 回呼函式: 探討了動態替換的方法與應用場景。
  • 實務範例: 介紹了 URL 操作與輸入淨化等實用技巧。
  • 最佳實踐: 說明了常見注意事項與效能相關的建議。

最後

JavaScript 的 replace() 方法是一個從基礎到進階都能廣泛應用的便利工具。未來我們將持續提供更多與 JavaScript 相關的實用資訊,敬請期待。
広告