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

如何优化React中字符串数组的拆分逻辑与渲染效果?

解决React中条款文本的编号与内容拆分问题

我帮你搞定这个问题!核心原因是你之前的拆分正则太宽泛了,会误匹配内容里的点或者冒号,导致整个字符串都被当成粗体部分。咱们换个思路,先精准捕获开头的编号部分,再分离内容就没问题了。

问题分析

原来的_.split(item, / \.|:/, 2)会匹配字符串中任意位置的空格加圆点,或者冒号。比如5. Terms and Conditions Title (dot at the end). Some general info here.里,标题末尾的. 会被当成分隔符,导致整个字符串被分到第一部分,全部变成粗体。

解决方案:精准匹配开头编号

我们可以用正则直接捕获开头的编号部分(比如5. 、6. ),剩下的内容不管包含什么符号,都统一作为普通文本。具体步骤:

  1. 用正则/^(\d+\. )(.*)/匹配主章节字符串:
    • ^(\d+\. ):匹配开头的1个或多个数字 + 圆点 + 空格,这是要加粗的编号部分
    • (.*):捕获编号之后的所有内容,不管里面有多少圆点、冒号或其他字符
  2. 额外添加子章节的匹配正则/^(\d+\.\d+\. )(.*)/,适配5.1. 这类层级编号
  3. 通过match方法提取这两部分,再分别渲染

修改后的代码

替换你原来的编号匹配逻辑块即可:

return (
  <div>
    {_.slice(_.map(example, (item, index) => {
      const key = index;
      if (index === 0) { // First text
        return (<h1 key={key}>{item}</h1>);
      }
      if (item === '') {
        return (<br key={key} />);
      }
      // 匹配主章节编号(如5. )
      const mainSectionMatch = item.match(/^(\d+\. )(.*)/);
      if (mainSectionMatch) {
        const [, boldNumber, content] = mainSectionMatch;
        return [
          <span className="bold" key={`bold-${key}`}>{boldNumber}</span>,
          <p className="normal" key={`normal-${key}`}>{content}</p>,
        ];
      }
      // 匹配子章节编号(如5.1. )
      const subSectionMatch = item.match(/^(\d+\.\d+\. )(.*)/);
      if (subSectionMatch) {
        const [, boldSubNumber, subContent] = subSectionMatch;
        return [
          <span className="bold" key={`bold-${key}`}>{boldSubNumber}</span>,
          <p className="normal" key={`normal-${key}`}>{subContent}</p>,
        ];
      }
      return (<p className="normal" key={key}>{item}</p>);
    }), startIndex, !_.isNil(endIndex) ? endIndex : _.size(example))}
  </div>
);

效果验证

测试你给出的例子:

  • 5. Terms and Conditions Title (dot at the end). Some general info here. 会拆成5. (粗体)和后面的全部内容(普通文本)
  • 6. Terms and Conditions Title ends with semi-column now: Some general info here. 会拆成6. (粗体)和后面的内容(普通文本)
  • 子章节5.1. Sub-section title. Some more info here.也会正确拆分5.1. 为粗体,其余为普通文本

这样就完美实现了你期望的渲染效果!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 09:06:06