I have lots of html image elements as a string but they often contain rubbish I don’t need. How can I remove titles, height, class etc?
Eg. <img class="img-fruit" src="apple.png" title="apple" height="25" width="25">
Would become
<img src="apple.png">
The order of attributes varies.
Struggling to think of an easy solution, any ideas?
I have tried searching for specific attributes and trying to calculate the lengths to remove them but it’s messy
>Solution :
You can use a regular expression to remove unwanted attributes from the HTML image elements string. Here’s a simple example in JavaScript 👇
const htmlString = ”;
const cleanedString = htmlString.replace(/(\s*(?:title|height|class)=[‘"][^’"]*[‘"])/g, ”);
console.log(cleanedString); //