Created
November 20, 2019 20:49
-
-
Save adrianbarwicki/5bc11e0d88ab504268eda61a8ff96a1a to your computer and use it in GitHub Desktop.
Extracts the first image url from a markdown text
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
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
commented
Nov 21, 2019
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment