You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用jQuery检测字符串指定字符并包裹<span>标签

jQuery实现指定字符包裹(避免innerHTML操作)

直接操作文本节点来实现需求,完全不用innerHTML,既安全又不会破坏原有DOM结构:

核心思路

遍历目标元素的纯文本节点,将匹配到的目标字符拆分成独立的<span>节点插入DOM,替换原文本节点,全程不涉及HTML字符串拼接。

代码实现

function wrapTargetChars(selector, targetChars) {
  // 转义正则特殊字符,避免匹配出错
  const escapedChars = targetChars.map(char => char.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'));
  // 生成大小写不敏感的匹配正则
  const matchRegex = new RegExp(`[${escapedChars.join('')}]`, 'gi');

  $(selector).contents().each(function() {
    // 只处理纯文本节点(nodeType=3),跳过元素节点
    if (this.nodeType === 3 && matchRegex.test(this.nodeValue)) {
      const originalText = this.nodeValue;
      let lastPosition = 0;
      const parentNode = this.parentNode;

      // 逐个匹配并替换字符
      originalText.replace(matchRegex, (matchedChar, index) => {
        // 插入匹配前的文本片段
        if (index > lastPosition) {
          parentNode.insertBefore(document.createTextNode(originalText.slice(lastPosition, index)), this);
        }
        // 创建包裹字符的span节点
        const spanNode = $('<span>').text(matchedChar)[0];
        parentNode.insertBefore(spanNode, this);
        lastPosition = index + matchedChar.length;
      });

      // 删除原文本节点
      parentNode.removeChild(this);
    }
  });
}

// 调用示例:给h4标签里的X、P字符加span包裹
wrapTargetChars('h4', ['x', 'p']);

关键细节

  • 自动转义正则特殊字符:如果目标字符是.、*这类正则元字符,也能正确匹配,不会出错。
  • 大小写不敏感:示例中的大写X、P都会被匹配包裹,如需严格大小写,去掉正则里的i标志即可。
  • 不破坏原有DOM:只操作文本节点,保留原元素的事件绑定、属性等,比innerHTML更安全可靠。

内容的提问来源于stack exchange,提问作者KLSVRT

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 06:25:21