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

使用正则表达式将特定类名p标签转换为ul-li结构的问题

问题:将特定类名的

标签转换为

    包裹的
  • 项

尝试用正则表达式把带有MsoListParagraphCxSpFirst/Middle/Last类名的<p>标签,转换成<ul>包裹的<li>项,但现有代码未生效,相关代码和标记如下:

现有代码

html = html.replace(/&lt;p class=&quot;MsoListParagraphCxSpFirst&quot;&gt;(.*?)&lt;/p&gt;/, '&lt;ul&gt;&lt;li&gt;$1&lt;/li&gt;');
html = html.replace(/&lt;p class=&quot;MsoListParagraphCxSpMiddle&quot;&gt;(.*?)&lt;/p&gt;/, '&lt;li&gt;$1&lt;/li&gt;');
html = html.replace(/&lt;p class=&quot;MsoListParagraphCxSpLast&quot;&gt;(.*?)&lt;/p&gt;/, '&lt;li&gt;$1&lt;/li&gt;&lt;ul&gt;');

当前标记

&lt;p class=&quot;MsoListParagraphCxSpFirst&quot;&gt;Item 1&lt;/p&gt;
&lt;p class=&quot;MsoListParagraphCxSpMiddle&quot;&gt;Item 2&lt;/p&gt;
&lt;p class=&quot;MsoListParagraphCxSpLast&quot;&gt;Item 3&lt;/p&gt;

期望标记

&lt;ul&gt;
    &lt;li&gt;Item 1&lt;/li&gt;
    &lt;li&gt;Item 2&lt;/li&gt;
    &lt;li&gt;Item 3&lt;/li&gt;
&lt;/ul&gt;

问题原因与修正方案

核心问题

  1. 未全局匹配:JavaScript的replace方法默认只替换第一个匹配项,未加g标志导致后面的<p>标签不会被处理
  2. 标签错误:最后一个替换中把闭合的</ul>写成了<ul>,导致结构错误
  3. 格式缺失:未处理换行和缩进,输出结果会挤在一起

修正后的代码

// 全局匹配所有目标标签,添加g标志;修正最后一个替换的闭合标签,同时加入格式换行
html = html.replace(/&lt;p class=&quot;MsoListParagraphCxSpFirst&quot;&gt;(.*?)&lt;\/p&gt;/g, '&lt;ul&gt;\n    &lt;li&gt;$1&lt;/li&gt;');
html = html.replace(/&lt;p class=&quot;MsoListParagraphCxSpMiddle&quot;&gt;(.*?)&lt;\/p&gt;/g, '\n    &lt;li&gt;$1&lt;/li&gt;');
html = html.replace(/&lt;p class=&quot;MsoListParagraphCxSpLast&quot;&gt;(.*?)&lt;\/p&gt;/g, '\n    &lt;li&gt;$1&lt;/li&gt;\n&lt;/ul&gt;');

说明

  • 每个正则末尾添加g(全局匹配)标志,确保替换所有符合条件的标签
  • 修正最后一个替换的闭合标签为</ul>,保证HTML结构合法
  • 在替换字符串中加入\n(换行)和空格,让输出的HTML结构和期望格式一致
  • 确保正则完整匹配闭合的&lt;/p&gt;标签,避免匹配不完整

测试结果

运行修正后的代码后,当前标记会被转换为符合期望的格式:

&lt;ul&gt;
    &lt;li&gt;Item 1&lt;/li&gt;
    &lt;li&gt;Item 2&lt;/li&gt;
    &lt;li&gt;Item 3&lt;/li&gt;
&lt;/ul&gt;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 19:20:29