这样的 HTML 正则怎么写?

const imgs = [{
    id: 1,
    content_type: 'image/jpeg',
    title: '图片1',
    url: 'https://xxx.com/001.jpg'
}, {
    id: 2,
    content_type: 'image/jpeg',
    title: '图片2',
    url: 'https://xxx.com/002.jpg'
}, {
    id: 3,
    content_type: 'image/jpeg',
    title: '图片3',
    url: 'https://xxx.com/003.jpg'
}, {
    id: 4,
    content_type: 'image/jpeg',
    title: '图片4',
    url: 'https://xxx.com/004.jpg'
}, {
    id: 5,
    content_type: 'application/pdf',
    title: '005.pdf',
    url: 'https://xxx.com/005.pdf'
}];

const html = '<p>文本文本文本文本文本</p><a data-type="image/jpeg" data-id="1" href="https://xxx.com/001.jpg" target="_blank"><img src="https://xxx.com/001.jpg" /></a><p>文本文本文本文本文本</p><a data-type="image/jpeg" data-id="2" href="https://xxx.com/002.jpg" target="_blank"><img src="https://xxx.com/002.jpg" /></a><a data-type="image/jpeg" data-id="3" href="https://xxx.com/003.jpg" target="_blank"><img src="https://xxx.com/003.jpg" /></a><a data-type="image/jpeg" data-id="4" href="https://xxx.com/004.jpg" target="_blank"><img src="https://xxx.com/004.jpg" /></a><a data-type="application/pdf" data-id="5" href="https://xxx.com/005.pdf" target="_blank">004.pdf</a>';

const html_change = '<p>文本文本文本文本文本</p><!-- 1 --><p>文本文本文本文本文本</p><!-- 2 --><!-- 3 --><!-- 4 --><!-- 5 -->';

htmlhtml_change 这两个数据,怎么相互转换。

html_change 里面的数字,就是 imgs 里面的 id;

如果是图片: <a data-type="image/jpeg" data-id="1" href="https://xxx.com/001.jpg" target="_blank"><img src="https://xxx.com/001.jpg" /></a>

其他那就是:<a data-type="application/pdf" data-id="5" href="https://xxx.com/005.pdf" target="_blank">004.pdf</a>

阅读 1.6k
1 个回答
html_change.replace(/<!-- (\d+) -->/g, (_, id) => {
    const it = img[+id]
    if (it.content_type === 'image/jpeg') return // ...
    // ...
})
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进