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

不使用innerHTML搭配replace方法的安全替代方案有哪些?

无innerHTML安全实现方案

你可以通过操作原生DOM节点的方式实现完全一致的效果,全程规避XSS注入风险,实现代码如下:

function identifier(reg, className) {
  const regex = new RegExp(reg, "gi");
  const pList = document.querySelectorAll("p");
  pList.forEach(p => {
    // 初始p仅含纯文本,直接读取文本内容
    const rawText = p.textContent;
    // 清空原有内容
    p.textContent = '';
    let lastMatchedIndex = 0;
    let matchResult;
    // 遍历所有匹配的标识符
    while ((matchResult = regex.exec(rawText)) !== null) {
      // 插入匹配项之前的普通文本
      if (matchResult.index > lastMatchedIndex) {
        p.appendChild(document.createTextNode(rawText.slice(lastMatchedIndex, matchResult.index)));
      }
      // 创建带指定类名的span包裹匹配内容
      const styleSpan = document.createElement('span');
      styleSpan.className = className;
      styleSpan.textContent = matchResult[0];
      p.appendChild(styleSpan);
      lastMatchedIndex = regex.lastIndex;
    }
    // 插入末尾未匹配的剩余文本
    if (lastMatchedIndex < rawText.length) {
      p.appendChild(document.createTextNode(rawText.slice(lastMatchedIndex)));
    }
  });
}
identifier("[^<>]+?:", "identifier");

方案优势

  • 全程使用textContent、createElement等原生DOM API,完全规避innerHTML带来的XSS注入风险,即使文本内容包含恶意代码也不会被执行
  • 匹配逻辑和最终渲染效果与你的原有代码完全一致
  • 适配你当前p标签仅含纯文本的场景,代码复杂度和原有实现基本持平

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 18:15:00