var $el = $('#content');
// 替換所有 'jb51'(不區分大小寫)
$el.html($el.html().replace(/jb51/ig, ''));
| 點 | 說明 |
|---|---|
.html() 獲取內部 HTML | 包含子標籤結構,替換會影響屬性值、標籤名,需謹慎 |
/ig 正則標誌 | i 忽略大小寫,g 全局匹配(否則僅替換首次) |
| 替換為空字符串 | 相當於刪除匹配文本 |
| 返回值 | replace 返回新字符串,原字符串不變,需重新 .html() 設置 |
避免誤替換標籤屬性、class 名、JS 代碼等:
$.fn.replaceText = function(search, replacement) {
return this.each(function() {
var $this = $(this);
$this.contents().filter(function() {
return this.nodeType === 3; // TextNode
}).each(function() {
this.nodeValue = this.nodeValue.replace(search, replacement);
});
});
};
// 使用:僅替換可見文本,不動屬性
$('#content').replaceText(/jb51/ig, '');
<!DOCTYPE html>
<html><head><meta charset="utf-8"><script src="https://cdn.jsdelivr.net/npm/jquery@3.7.1/dist/jquery.min.js"></script></head><body>
<div id="content">
<p>歡迎訪問 jb51.net,這裡有 jb51 教程。</p>
<a href="https://jb51.net" class="jb51-link">鏈接</a>
<span data-id="jb51-123">數據屬性</span>
</div>
<button id="btn1">簡單 replace(會誤傷屬性)</button>
<button id="btn2">安全 replaceText(僅文本節點)</button>
<script>
$.fn.replaceText = function(search, replacement) {
return this.each(function() {
$(this).contents().filter(function() { return this.nodeType === 3; })
.each(function() { this.nodeValue = this.nodeValue.replace(search, replacement); });
});
}
$('#btn1').click(function() {
var $el = $('#content');
$el.html($el.html().replace(/jb51/ig, '[已屏蔽]'));
});
$('#btn2').click(function() {
$('#content').replaceText(/jb51/ig, '[已屏蔽]');
});
</script>
</body></html>
$.fn.highlight = function(keyword, className) {
className = className || 'highlight';
var regex = new RegExp('(' + keyword.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + ')', 'ig');
return this.replaceText(regex, '<span class="' + className + '">$1</span>');
};
// 使用
$('#content').highlight('jb51', 'kw-highlight');
配合 CSS:.kw-highlight { background: #ff0; padding: 0 2px; border-radius: 2px; }
$el.html($el.html().replace(/regex/g, '')) 最快。TreeWalker API 或 Web Worker 避免主線程阻塞。