Remove <p> tags surrounding <img> tags generated by parsing markdown with Showdown

When Showdown makes image tags from your markdown, it wraps them in a paragraph tag.

To remove these non-essential p tags, which in my case made images a pain to style, define a new extension whereever your main converter is defined.

showdown.extension("remove-p-from-img", function () {
return [
{
type: "output",
filter: function (text) {
text = text.replace(
// match all <p>'s before and after an <img> tag
/(<\/?p[^>]*>)(?=<img.+>)|(<\/?p[^>]*>)(?<=<img.+>)/g,
""
);

return text;
},
},
];
});

const converter = new showdown.Converter({
extensions: ["remove-p-from-img"],
});

See the regular expression explained more clearly at RegExr