简体   繁体   English

Javascript 正则表达式 - 仅将一个字符添加到匹配的字符串

[英]Javascript Regex - add only a character to matched string

I am trying to create a JS regex that matches aa string inside a given piece of code by it's beggining and ending and then only adds one character to that matched string.我正在尝试创建一个 JS 正则表达式,它通过开始和结束来匹配给定代码段中的字符串,然后只向匹配的字符串添加一个字符。

Please see below what I mean:请看下面我的意思:

Imagine that I supply the following code:想象一下,我提供以下代码:

<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>

What I need to do is to have the script finding all instances of <img> and add a closing slash to the <img> elements so I would have something like this:我需要做的是让脚本找到<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>

Any help will be appreciated.任何帮助将不胜感激。

Regards, T问候,T

Usually regex should be avoided for dealing with html/xml, but since your img tag seems broken and img tags are not nested, you can use following regex,通常应该避免使用正则表达式来处理 html/xml,但是由于您的img标签似乎已损坏并且img标签没有嵌套,您可以使用以下正则表达式,

(<img[^>]*)>

and replace it with并将其替换为

$1 />

and fix your broken img tags.并修复损坏的img标签。

Demo演示

 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"> </div>` console.log('Before: ' + s); console.log('After: ' + s.replace(/(<img[^>]*)>/g,'$1 />'));

Just select the img and its content in a group (<img\s.*?) except the closing tag and use replace with a global flag to replace after it with / slash.只需 select 将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)

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

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