I have a generated string like this
tesgddedd<br> <div><img style="max-width: 10rem;" src="folder/mypicture.jpg"><div> <br></div></div>
I want to get the div containing the img and add a css class in this div to get a new string like this
tesgddedd<br> <div class="myCssClass"><img style="max-width: 10rem;" src="folder/mypicture.jpg"><div> <br></div></div>
I tried this method
let myString = 'tesgddedd<br> <div><img style="max-width: 10rem;" src="folder/mypicture.jpg"><div> <br></div></div>' console.log('My new String with div class : ',myString.match(/<div [^>]*img="[^"]*"[^>]*>/gm)[0])
It doesn't work.
What should I do?
It is recommended to use an HTML parser instead of regular expressions and use
.querySelector
to get thediv
withimg
.Use native browser interfaces DOMParser and .parseFromString to parse HTML.
The code snippet below is a visual example