將字符串中所有匹配正則的關鍵字用 <span> 包裹,如 world → <span>world</span>。
var re = /(world|people|Pizar)/g; // 關鍵:括號形成捕獲組
var str = "Disney films are favored by people all around the world, it is known to all that many of the movies are produced by Pizar animation studio";
var result = str.replace(re, '<span>$1</span>');
// $1 代表第一個捕獲組匹配的文本
console.log(result);
// 輸出: Disney films are favored by <span>people</span> all around the <span>world</span>, ... <span>Pizar</span> animation studio
(...) 括起要保留的部分,$1、$2... 對應第 1、2 個組。$& 整個匹配,$` 匹配前文本,$' 匹配後文本,$$ 字面美元符。var result = str.replace(re, function(match, p1, offset, string) {
return '<span class="kw-' + p1.toLowerCase() + '">' + match + '</span>';
});
若關鍵字包含正則元字符(如 . * ?),需先轉義:keywords.map(k => k.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))。