javascript正则表达式-添加结束img标签 [英] javascript regex - add closing img tag

查看:91
本文介绍了javascript正则表达式-添加结束img标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要添加一个结束图像标签.当前html:

I need to add a closing image tag. Current html:

<img class="logoEmail" src="/images/logoPDF.png">

我想要什么:

<img class="logoEmail" src="/images/logoPDF.png"/>

我该怎么做?

推荐答案

myInput ='<img class="example1" src="/images/example1.png">';
myInput += '<img class="example2" src="/images/example2.png"/>';

result = myInput.replace(/(<img("[^"]*"|[^\/">])*)>/gi, "$1/>");

正则表达式的解释:

< img 开始

"[^"] *"标签内的字符串.可能包含/字符.

"[^"]*" A string inside the tag. May contain the / character.

[^ \/>]] 其他(不是字符串,不是/,也不是标签的结尾)

[^\/">] Anything else (not a string, not a / and not the end of the tag)

> IMG标签的结尾

这只会匹配未完成的标签,并将其替换为整件事,再加上/>

This will only match unfinished tags, and will replace it by the whole thing, plus a />

正如我之前所说的,这不是防弹的,可能没有正则表达式可以100%起作用.

As I said before this is NOT bulletproof, probably there is no regex that would work 100%.

这篇关于javascript正则表达式-添加结束img标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆