Created
February 15, 2021 16:59
-
-
Save jagoncalves14/685e7fa56a9b836180fb256d8d4e884c to your computer and use it in GitHub Desktop.
Convert URL to Embed Media URL
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
/** | |
* Converts regular YouTube and Vimeo URLs | |
* into valid embed media urls to be used on iframes. | |
* The regex's are based on these two links: | |
* - https://gist.github.com/harisrozak/a34fce1899ae9458d700 | |
* - https://stackoverflow.com/a/22667308 | |
*/ | |
export const convertToEmbedMediaURL = (url: string): string => { | |
const YOUTUBE_PATTERN_REG = /^.*(?:http?s?:\/\/)?(?:www\.)?(?:youtube\.com|youtu\.be)\/(?:watch\?v=|embed\/|v\/|user\/.+\/)?([^\?&"]+).*$/ | |
const isYouTubeURL = YOUTUBE_PATTERN_REG.test(url) | |
if (isYouTubeURL) { | |
return url.replace(YOUTUBE_PATTERN_REG, 'https://www.youtube.com/embed/$1') | |
} | |
const VIMEO_PATTERN_REG = /^(?:http?s?:)?\/\/(?:www\.)?vimeo\.com\/([^\?&"]+).*$/ | |
const isVimeoURL = VIMEO_PATTERN_REG.test(url) | |
if (isVimeoURL) { | |
return url.replace(VIMEO_PATTERN_REG, 'https://player.vimeo.com/video/$1') | |
} | |
return url | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment