我正在尝试创建一个JS正则表达式,该正则表达式与给定代码中的字符串匹配,因为它正在乞讨和结束,然后只向匹配的字符串添加一个字符。
请看下面我的意思:
假设我提供了以下代码:
<div>
<p>This is just some random text</p>
<a href="https://somerandomsrc.com">
<img src="https://somerandomsrc.com" alt="random image">
</a>
<img src="https://someotherrandomsrc.com" alt="another random image">
</div>我需要做的是让脚本找到<img>的所有实例,并向<img>元素添加一个结束斜杠,这样我就可以得到如下内容:
<div>
<p>This is just some random text</p>
<a href="https://somerandomsrc.com">
<img src="https://somerandomsrc.com" alt="random image" />
</a>
<img src="https://someotherrandomsrc.com" alt="another random image" />
</div>任何帮助都将不胜感激。
你好,T
发布于 2022-08-25 21:15:13
通常,在处理html/xml时应该避免regex,但是由于img标记似乎被破坏了,并且img标记没有嵌套,所以可以使用以下regex,
(<img[^>]*)>并代之以
$1 />修复你破损的img标签。
const s = `<div>
<p>This is just some random text</p>
<a href="https://somerandomsrc.com">
<img src="https://somerandomsrc.com" alt="random image">
</a>
<img src="https://someotherrandomsrc.com" alt="another random image">
<img src="https://someotherrandomsrc.com" alt="another random image" />
</div>`
console.log('Before: ' + s);
console.log('After: ' + s.replace(/(<img[^>]*[^/])>/g,'$1 />'));
Edit1:
是的,只需将正则表达式更改为(<img[^>]*[^/])>,这样它就不会与已经有适当的结束标记/>的正则表达式匹配。
发布于 2022-08-25 21:16:09
只需在组img中选择(<img\s.*?)及其内容,除了结束标记外,然后使用带有全局标志的replace替换为/斜杠。
const string = `<div>
<p>This is just some random text</p>
<a href="https://somerandomsrc.com">
<img src="https://somerandomsrc.com" alt="random image">
</a>
<img src="https://someotherrandomsrc.com" alt="another random image">
</div>`
const result = string.replace(/(<img\s.*?)>/g, '$1 />')
console.log(result)
https://stackoverflow.com/questions/73493704
复制相似问题