简体   繁体   English

javascript regex - 添加结束 img 标签

[英]javascript regex - add closing img tag

I need to add a closing image tag.我需要添加一个结束图像标签。 Current html:当前的 html:

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

What I want:我想要的是:

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

How can I do that?我怎样才能做到这一点?

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

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

Explanation of the regex:正则表达式的解释:

<img The start <img开始

"[^"]*" A string inside the tag. May contain the / character. "[^"]*"标签内的字符串。可能包含/字符。

[^\\/">] Anything else (not a string, not a / and not the end of the tag) [^\\/">]其他任何东西(不是字符串,不是/也不是标签的结尾)

> The end of an IMG tag > IMG 标签的结尾

This will only match unfinished tags, and will replace it by the whole thing, plus a />这只会匹配未完成的标签,并将替换为整个事物,加上一个/>

As I said before this is NOT bulletproof, probably there is no regex that would work 100%.正如我之前所说,这不是万无一失的,可能没有 100% 有效的正则表达式。

You could try this regex also,你也可以试试这个正则表达式,

result = myInput.replace(/^([^\.]*\.[^>]*)(.*)$/g, "$1/$2");

DEMO演示

It captures all the characters upto a literal dot and stored it into a group.它将所有字符捕获到一个文字点并将其存储到一个组中。 Then it again captures characters upto > and stored into another group.然后它再次捕获字符>并存储到另一个组中。 Add a / in between the captured groups in the replacement part will give you the desired output.在替换部分的捕获组之间添加/将为您提供所需的输出。

It can be as easy as this:它可以像这样简单:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Demo Replace IMG tags w/ regex</title>
    <script type="text/javascript">
        window.onload = function() {
            document.body.innerHTML = document.body.innerHTML.replace(/(<img[^>]+)/g, "$1 /");
        }
    </script>
</head>
<body>
    <p>Some text.</p>
    <img src="images/logoPhone.jpg">
        <br>
    <img src="images/logoMail.png">
    <p>Some more text.</p>
</body>
</html>

. .
Explanation:解释:

<img : match must start with this. <img :匹配必须以此开头。
[^>] : after the starting match, the next character may be anything but >. [^>] : 开始匹配后,下一个字符可以是除 > 之外的任何字符。
+ : one or more occurances. + :出现一次或多次。
g : apply globally, do not return on the first match. g : 全局应用,第一次匹配时不返回。
$1 : as in the first capture group (= stuff between first set of parentheses). $1 :如第一个捕获组(=第一组括号之间的内容)。
. .

Be aware that Firebug never shows closing slashes, regardless of doctype.请注意,无论文档类型如何,Firebug 都不会显示关闭斜杠。 But you can see the regex script in action here: http://regex101.com/r/zS2zO1 .但是您可以在此处查看正在运行的正则表达式脚本: http : //regex101.com/r/zS2zO1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM