Home > other >  Javascript Regex - add only a character to matched string
Javascript Regex - add only a character to matched string

Time:08-26

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

CodePudding user response:

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">
    <img src="https://someotherrandomsrc.com" alt="another random image" />
</div>`

console.log('Before: '   s);
console.log('After: '   s.replace(/(<img[^>]*[^/])>/g,'$1 />'));

Edit1:

Yes just change the regex to (<img[^>]*[^/])> so that it won't match the one which already has a proper closing tag />.

Updated Demo

CodePudding user response:

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.

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)

  • Related