首页 > 解决方案 > 如何重写 HTML 替换与子标签相同的父标签?

问题描述

我正在从 API 读取一堆 html 内容

[
    {
        id: 1,
        content: '{html...}'
    },
    {
        id: 2,
        content: '{html...}'
    }
]

获得这些数据后,我使用sanitize-html进行了一些替换。但现在我必须做一些额外的工作。

有时我得到这个

<p>some text...<p>
<p>
    <p>some text...<p>
    <p>
        <img />
        <span>some text</span>
    <p>
<p>

或这个

<p>some text...<p>
<p>some text...<p>
<p>
    <img />
    <span>some text</span>
<p>

我假装做的事情是让我的段落保持在一个级别,所以我想使用cheerio(它使用jQuery核心),做类似的事情

const cheerio = require('cheerio');
const $ = cheerio.load(content);
content = $('p:not(:has(>p))').html();

但这只会带来第一个p且仅在存在时。如果我手动获取其他内容,我可能会丢失内容的正确顺序。

p那么,根据我的示例,是否有一种清理 HTML 的好方法,只保留一个级别?

标签: jqueryhtmlcheerio

解决方案


您的 HTML 无效。

  • 一个p元素可能不包含一个p元素
  • 的结束标签p是可选的
  • 试图把一个p放在另一个里面p会隐式地关闭第一个p
  • 额外的结束标签将被忽略

这个程序:

const content = `

<p>some text...<p>
<p>
    <p>some text...<p>
    <p>
        <img />
        <span>some text</span>
    <p>
<p>


`;

const cheerio = require('cheerio');
const $ = cheerio.load(content);
console.log($.html());

将输出:

<html><head></head><body><p>some text...</p><p>
</p><p>
    </p><p>some text...</p><p>
    </p><p>
        <img>
        <span>some text</span>
    </p><p>
</p><p>


</p></body></html>

因此,只需调用$.html()将使段落嵌套变平。


推荐阅读