i have a generated string like it
tesgddedd<br> <div><img style="max-width: 10rem;" src="folder/mypicture.jpg"><div> <br></div></div>
I want to get div contains img and to add css class in this div et to have a new string liket it
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.
How can I do it please ?
2
Answers
Recommend using an HTML parser instead of regex and using
.querySelector
to grab thediv
withimg
.See below snippet to visually see it work.
To add a CSS class to the containing the , you can use regular expressions in JavaScript. Here’s an example of how you can achieve it:
Please note that manipulating HTML strings with regular expressions can be error-prone, especially for complex HTML structures. It’s generally recommended to use a proper HTML parser or DOM manipulation library for more reliable and maintainable results.