如何用javascript解析html判断该元素最后有没有加上 / >

希望能够利用javascript解析html字串,判断所有的<img>元素,如果结尾有加上/>,就像是<img />的话,就删除。
假设现在有一组字串:

<h1>h1</h1>
<img id="a" src="https://placehold.it/200x200" alt="" />
<h2>h2</h2>
<img id="b" src="https://placehold.it/200x200" alt="">

希望能够改为

<h1>h1</h1>
<img id="a" src="https://placehold.it/200x200" alt="">
<h2>h2</h2>
<img id="b" src="https://placehold.it/200x200" alt="">

我尝试使用jquery做判断,发现读入jquery时,似乎好像已经被标准化了,无法从jquery对象中判断原本的img tag 的html。

html

<img id="a" src="https://placehold.it/200x200" alt="" /> 
<img id="b" src="https://placehold.it/200x200" alt="">

javascript

console.log($("#a"));
console.log($("#b")); 

两个打印出来的元素是一模一样的。

在python中的beautifulSoup和tag中,有个接口叫做isSelfClosing正是我需要的,请问这个在javascript有类似的库和接口吗?我找了jquery和cheerio的文档都没找到

阅读 3.7k
2 个回答

这样可以实现,你复制到浏览器试试,可能不一定能达到你想要的效果,不过可以做到你说的那样.

document.body.innerHTML.match(/(<img.*?>)/mg).map((item)=> item.replace(/(?=.*?)\/>$/, '>'))

将原 HTML 中不合规的 img 标签全部替换

'原 HTML'.replace(/(<img.*?>)/mg, (item) => item.replace(/(?=.*?)\/>$/, '>'))

经@tengqingya提醒,修改了一下

原答案

document.body.innerHTML.match(/(<img.*?>)/mg).map((item)=> item.replace(/(?=.*?)\/?>$/, '')+'>')

JS 应该无法通过 DOM 判断,只能通过字符串匹配了。

但你无需判断是不是,全都获取 outerHTML 就可以得到没有 self-closing 的标签。

反过来如果需要都加上的可以参考

var XMLS = new XMLSerializer(); 
XMLS.serializeToString(el)
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题