字串的 replace() 方法用來搜尋並替換內容。範例把段落中的 "Microsoft" 換成 "poluoluo.com"。
<!DOCTYPE html>
<html>
<body>
<p>Click the button to replace "Microsoft" with "poluoluo.com" 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", "poluoluo.com");
document.getElementById("demo").innerHTML = n;
}
</script>
</body>
</html>
一、預設只換第一個。字串參數只會替換第一個符合項:
"a-b-c".replace("-", "+"); // "a+b-c"
二、要全部替換,用正則的 g 旗標。
"a-b-c".replace(/-/g, "+"); // "a+b+c"
// ES2021 起也有專用方法:
"a-b-c".replaceAll("-", "+"); // "a+b+c"
三、字串是 immutable 的。replace() 不會改動原字串,而是回傳新字串。範例中必須把結果寫回 innerHTML,正是這個原因。
"John Smith".replace(/(\w+)\s(\w+)/, function (m, first, last) {
return last + ", " + first;
});
// "Smith, John"
實務上最該留意的是安全性:範例把結果寫回 innerHTML,若被替換進來的內容來自使用者輸入,就可能形成 XSS。純文字替換請改用 textContent。