I am trying to create a JS regex that matches a a string inside a given piece of code by it’s beggining and ending and then only adds one character to that matched string.
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:
<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
>Solution :
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,
(<img[^>]*)>
and replace it with
$1 />
and fix your broken img tags.
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 />'));