Skip to content

Instantly share code, notes, and snippets.

@riccjohn
Last active February 5, 2025 22:31
Show Gist options
  • Select an option

  • Save riccjohn/d3116ee27b2eaeab763721699b66e9e4 to your computer and use it in GitHub Desktop.

Select an option

Save riccjohn/d3116ee27b2eaeab763721699b66e9e4 to your computer and use it in GitHub Desktop.
Convert markdown images to html image tags
type Options = {
width?: number;
height?: number;
class?: string;
};
const convertMdImgToHtml = (markdownImages: string[], options?: Options) => {
const convertedImages = markdownImages.map((markdownImage) => {
return markdownImage.replace(
/!\[(.*?)\]\((.*?)\)/g,
(_match, altText, imageUrl) => {
let imgTag = `<img src="${imageUrl}" alt="${altText}"`;
if (options) {
for (const key in options) {
if (options.hasOwnProperty(key)) {
const value = options[key as keyof Options];
if (value !== null) {
imgTag += ` ${key}="${value}"`;
}
}
}
}
imgTag += ' />';
return imgTag;
}
);
});
return convertedImages.join('\n');
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment