DIV CSS 佈局教程網

replace:把字串中的指定內容換掉
編輯:關於JavaScript     

字串的 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。

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