萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

jQuery 替換指定元素內文本內容:html() + replace 組合與正則全局替換技巧

核心代碼

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, '')) 最快。
  • 混合 HTML 結構、需保護屬性:遍歷 TextNode 替換 nodeValue 唯一正確方案。
  • 高亮/包裹標籤:同理操作 TextNode,替換為帶標記的 HTML 片段。
  • 大規模文本處理:考慮 TreeWalker API 或 Web Worker 避免主線程阻塞。
copyright © 萬盛學電腦網 all rights reserved