Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript Regex – add only a character to matched string

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

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 />'));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading