Last active
November 3, 2018 05:56
-
-
Save tlhunter/d42bcf6cea2654abc08248031830f917 to your computer and use it in GitHub Desktop.
Replace GitHub Gist's, YouTube, Vimeo URLs with their embed equivalent
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 function accepts text which is to be transformed into HTML. When | |
* it encounteres a line which simply contains a single URL it will replace | |
* that URL with an HTML tag to embed the corresponding resource. | |
* | |
* Supported services: | |
* - GitHub Gists | |
* - YouTube Videos | |
* - Vimeo Videos | |
*/ | |
const GIST = /^(https:\/\/gist\.github\.com\/[a-zA-Z0-9_-]+\/[a-z0-9]+)$/gm; | |
const VIMEO = /^https:\/\/vimeo\.com\/([0-9]+)$/gm; | |
const YOUTUBE = /^https:\/\/www\.youtube\.com\/watch\?v=([0-9A-Za-z-_]+)$/gm; | |
const WIDTH = 640; | |
const HEIGHT = 480; | |
function gist(input, width, height) { | |
return input.replace( | |
GIST, | |
'<script src="$1.js"></script>' | |
); | |
} | |
function vimeo(input, width, height) { | |
return input.replace( | |
VIMEO, | |
`<iframe class="video-embed" width=\"${width}\" height=\"${height}\" src=\"https://player.vimeo.com/video/$1?app_id=122963\" frameborder=\"0\" allow=\"fullscreen\" allowfullscreen></iframe>` | |
); | |
} | |
function youtube(input, width, height) { | |
return input.replace( | |
YOUTUBE, | |
`<iframe class="video-embed" width=\"${width}\" height=\"${height}\" src=\"https://www.youtube.com/embed/$1?feature=oembed\" frameborder=\"0\" allow=\"fullscreen\" allowfullscreen></iframe>` | |
); | |
} | |
const TASKS = [ gist, vimeo, youtube ]; | |
module.exports = function (html, width, height) { | |
for (let task of TASKS) { | |
html = task(html, width || WIDTH, height || HEIGHT); | |
} | |
return html; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example Usage:
Example Output: