Skip to content

Instantly share code, notes, and snippets.

@adrianbarwicki
Created November 20, 2019 20:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adrianbarwicki/5bc11e0d88ab504268eda61a8ff96a1a to your computer and use it in GitHub Desktop.
Save adrianbarwicki/5bc11e0d88ab504268eda61a8ff96a1a to your computer and use it in GitHub Desktop.
Extracts the first image url from a markdown text
/**
Extracts the first image url from a markdown text
Copyright 2019 Adrian Barwicki
*/
const IMAGE_EXTENSIONS = ["jpeg", "jpg", "png", "gif"];
const getExtension = (path: string): string => {
return path.split(".").pop();
};
/**
* Extracts the first image url from a markdown text
* @param bodyMD markdown text
* @returns extracts the first image url found in the text
*/
export const extractImageUrlFromMarkdown = (
bodyMD: string
): string | undefined => {
// extracts ![]() from markdown
const matches = bodyMD.match(/(?:!\[(.*?)\]\((.*?)\))/g);
if (!matches) {
return undefined;
}
return (
matches
// maps ![]() to urls
.map(match => {
const matches = match.match(/\((.*?)\)/g);
return matches.map(b => b.replace(/\(|(.*?)\)/g, "$1"))[0];
})
// finds the first url with the specifed extension
.find(url => {
return (
url && IMAGE_EXTENSIONS.indexOf(getExtension(url)) !== -1
);
})
);
};
@doublemarked
Copy link

function extractImageUrlFromMarkdown(content) {
    return (content.match(/!\[.+?\]\((.*?(?:\.jpe?g|png|gif))\)/i) || [])[1]
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment