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

如何使用JavaScript将带数字序号的单行文本转换为有序列表

问题原因

  • 你的正则只实现了单个列表项转<li>标签的逻辑,没有补充外层<ol>标签的包裹步骤,自然不会生成外层标签。
  • 你写的/\d\.([\s\w]+)/g正则存在匹配范围缺陷:[\s\w]只能匹配空白字符、字母、数字和下划线,遇到原文里的冒号、逗号、单引号等标点就会终止匹配,最终替换出来的<li>内容是不完整的。

解决方案

修正正则匹配规则,匹配每个数字序号到下一个序号(或文本末尾)的全部内容,替换为<li>后整体包裹<ol>即可,示例代码如下:

// 原始API返回文本
const rawText = "1. Choose a target. Pick a target within your attack's range: a creature, an object, or a location. 2. Determine modifiers. The GM determines whether the target has cover and whether you have advantage or disadvantage against the target. In addition, spells, special abilities, and other effects can apply penalties or bonuses to your attack roll. 3. Resolve the attack. You make the attack roll. On a hit, you roll damage, unless the particular attack has rules that specify otherwise. Some attacks cause special effects in addition to or instead of damage。";

// 匹配规则:数字+圆点开头,捕获内容直到下一个数字+圆点或文本结尾
const liContent = rawText.replace(/\d+\.\s*(.*?)(?=\s*\d+\.|$)/g, "<li>$1</li>");
// 外层包裹ol标签
const finalHtml = `<ol>${liContent}</ol>`;

运行后finalHtml就是符合要求的标准有序列表代码。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 12:15:02