Skip to content

Instantly share code, notes, and snippets.

@zadeviggers
Last active June 22, 2022 23:56
Show Gist options
  • Save zadeviggers/82cc330a4275af15b94e296b8fbcd7ad to your computer and use it in GitHub Desktop.
Save zadeviggers/82cc330a4275af15b94e296b8fbcd7ad to your computer and use it in GitHub Desktop.
A function to embed yotube videos in markdown
// This code looks for syntax like `{{youtube: https://www.youtube.com/watch?v=dQw4w9WgXcQ}}`
// rather than a plain URL, but it should be simple enough to modify the regex.
// Call this function on your raw markdown before your markdown processor (e.g. Marked, ReMark, etc) is run on it,
// and then pass the output of this function to your markdown processor.
function embedYoutubeVideos(md: string): string {
const ytRegexGlobal = /{{youtube: ?([^{}]+)}}/g;
const matches = md.matchAll(ytRegexGlobal);
let output = md;
try {
for (const match of matches) {
const video = new URL(match[1]);
let videoID = video.searchParams.get("v");
if (!videoID && video.hostname.includes("youtu.be")) {
videoID = video.pathname.split("/")[1];
}
if (!videoID) return output;
output = output.replace(
match[0],
`<iframe class="youtube-video" type="text/html" width="560" height="315" src="https://www.youtube.com/embed/${videoID}" frameborder="0" allow=" autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>\n`,
);
}
} catch (err) {
return output;
}
return output;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment