Last active
June 22, 2022 23:56
-
-
Save zadeviggers/82cc330a4275af15b94e296b8fbcd7ad to your computer and use it in GitHub Desktop.
A function to embed yotube videos in markdown
This file contains hidden or 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
// 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