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

How can I strip attributes from a html image string and only keep the source?

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

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

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); //

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