replace() 是字串替換的基礎方法,但預設**只替換第一個匹配**。ES2021 新增 replaceAll() 可一次替換所有匹配。本文詳細說明兩者語法、正則運用與常見陷阱。
str.replace(searchFor, replaceWith)
str.replaceAll(searchFor, replaceWith)
const str = 'Visit Microsoft! Visit Microsoft!';
console.log(str.replace('Microsoft', 'jb51.net'));
// "Visit jb51.net! Visit Microsoft!"
console.log(str.replace(/Microsoft/g, 'jb51.net'));
// "Visit jb51.net! Visit jb51.net!"
console.log(str.replaceAll('Microsoft', 'jb51.net'));
// "Visit jb51.net! Visit jb51.net!"
const str = 'apple, banana, apple';
const result = str.replaceAll('apple', (match, offset, whole) => {
return match.toUpperCase() + `(${offset})`;
});
console.log(result); // "APPLE(0), banana, APPLE(18)"
<!DOCTYPE html>
<html>
<body>
<p id="demo">Visit Microsoft!</p>
<button onclick="replaceText()">替換</button>
<script>
function replaceText() {
const el = document.getElementById('demo');
el.innerHTML = el.innerHTML.replaceAll('Microsoft', 'jb51.net');
}
</script>
</body>
</html>
| 模式 | 意義 |
|---|---|
| $$ | 插入 "$" |
| $& | 插入匹配的子字串 |
| $` | 插入匹配前的字串 |
| $' | 插入匹配後的字串 |
| $n | 第 n 個捕獲群組 (正則時) |
| $<Name> | 具名捕獲群組 (ES2018) |
'John Smith'.replace(/(\w+)\s(\w+)/, '$2, $1'); // "Smith, John"
str.replace(/abc/, 'x') 只替第一個。str = str.replaceAll(...)。replaceAll 為 ES2021 標準,舊環境可用 Polyfill:
if (!String.prototype.replaceAll) {
String.prototype.replaceAll = function(search, replace) {
if (search instanceof RegExp) {
if (!search.global) throw new TypeError('replaceAll requires global RegExp');
return this.replace(search, replace);
}
return this.replace(new RegExp(search.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'g'), replace);
};
}
現代開發請優先使用 replaceAll() 進行全域字串替換,語意明確且不需正則轉義。需複雜模式匹配時搭配正則 replace(/pattern/g, ...)。永遠記得:字串不可變,回傳值才是結果。