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

使用html-react-parse解析含(e.g.,)文本时触发DOMException错误

问题分析

你遇到的错误是因为html-react-parser和react-html-parse的底层解析器会误将文本中(e.g.,这类括号开头的内容识别为无效HTML标签,进而抛出创建元素失败的异常。

解决方案

方案1:预处理文本转义圆括号

通过将圆括号转换为HTML实体,避免解析器误判为HTML标签起始符,同时保留合法的HTML标签解析:

import React from "react";
import parse from 'html-react-parser';

export function App(props) {
  function getSearchHighlight(highlight) {
    try {
      // 转义圆括号为HTML实体,阻止解析器误判
      const processedText = highlight
        .replace(/\(/g, '(')
        .replace(/\)/g, ')');
      return parse(processedText);
    } catch (e) {
      return "Issues with search highlight " + e;
    }
  }

  return (
    <div className="App">
      <h1>Hello React Parse.</h1>
      <p>
        {getSearchHighlight(
          "Comparison to this and that <em>information</em> (e.g., those surveys)."
        )}
      </p>
    </div>
  );
}

方案2:用解析器替换回调拦截无效标签

利用html-react-parser的replace配置,捕获解析器识别的无效标签,将其转换为对应文本内容:

import React from "react";
import parse from 'html-react-parser';

export function App(props) {
  function getSearchHighlight(highlight) {
    try {
      return parse(highlight, {
        replace: (domNode) => {
          // 仅允许解析<em>标签,其他识别出的标签转为带括号的文本
          if (domNode.type === 'tag' && domNode.name !== 'em') {
            return `(${domNode.name})`;
          }
        }
      });
    } catch (e) {
      return "Issues with search highlight " + e;
    }
  }

  return (
    <div className="App">
      <h1>Hello React Parse.</h1>
      <p>
        {getSearchHighlight(
          "Comparison to this and that <em>information</em> (e.g., those surveys)."
        )}
      </p>
    </div>
  );
}
方案说明
  • 方案1从根源避免误判,适合包含多种括号类文本的通用场景;
  • 方案2精准拦截无效标签,适合明确知道需要保留哪些HTML标签的场景;
  • 两种方案均无需使用dangerouslySetInnerHTML,同时能正常解析<em>这类合法高亮标签。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 02:52:51