我使用Cheerio JS简化一些古老的HTML代码并将其转换为HTML5。除此之外,我还替换了一些标记过多的引号,如下所示:
要替换的节点:
<div style="margin:20px; margin-top:5px; ">
<div class="smallfont" style="margin-bottom:2px">Quote:</div>
<table cellpadding="6" cellspacing="0" border="0" width="100%">
<tbody>
<tr>
<td class="alt2" style="border:1px solid #999">
<div>
Originally Posted by <strong>Username</strong>
</div>
<div style="font-style:italic">Lorem ipsum dolor sit amet</div>
</td>
</tr>
</tbody>
</table>
</div>
转换后的输出应该如下所示:
<blockquote>Lorem ipsum dolor sit amet</blockquote>
下面是我目前使用的代码:
$(`table[id^='post']`).each( (i, el) => {
// Get the post
let postBody = $(el).find(`div[id^='post_message_']`).html().trim();
// Replace quotes with blockquotes
cheerio.load(postBody)('div[style^="margin:20px; margin-top:5px; "]').each( (i, el) => {
if ($(el).html().trim().startsWith('<div class="smallfont" style="margin-bottom:2px">Quote')) {
let tbody = $(el).find('tbody > tr > td').html();
let quote = $(el).find('tbody > tr > td > div');
if (quote.html() && quote.text().trim().startsWith('Originally Posted by')) {
let replacement = $('<blockquote>Hello</blockquote>');
quote.parent().html().replace(quote.html(), replacement);
}
// Looks all good
console.log($(el).html())
}
postBody = $(el).html();
});
});
最后,更多的HTML用于某些上下文:
<div id="post_message_123456">
As Username has previously written
<br>
<div style="margin:20px; margin-top:5px; ">
<div class="smallfont" style="margin-bottom:2px">Quote:</div>
<table cellpadding="6" cellspacing="0" border="0" width="100%">
<tbody>
<tr>
<td class="alt2" style="border:1px solid #999">
<div>
Originally Posted by <strong>Username</strong>
</div>
<div style="font-style:italic">Lorem ipsum dolor sit amet</div>
</td>
</tr>
</tbody>
</table>
</div>
<br>
I think he has a point!
<img src="smile-with-sunglasses.gif" />
</div>
替换本身看起来工作正常,console.log()
语句的输出看起来一切正常。问题出在最后一行,我试图用替换来替换原始内容。然而,postBody
看起来像以前一样。我做错了什么?
2条答案
按热度按时间7eumitmz1#
试试这样:
jqjz2hbq2#
根据具体上下文替换项目
这演示了如何将不安全的URL替换为安全的URL,作为一个有用的现实示例,并且对于大多数普通人来说,做出编程决策比使用regex要容易得多。