javascript
Back to Snippets
Extract YouTube & Vimeo Video IDs
Parse video IDs from YouTube and Vimeo URLs and generate embed URLs.
javascript
function getYoutubeId(url) {
const match = url.match(
/(?:youtu\.be\/|youtube\.com\/(?:embed\/|v\/|watch\?v=|watch\?.+&v=))([\w-]{11})/
)
return match ? match[1] : null
}
function getVimeoId(url) {
const match = url.match(/vimeo\.com\/(\d+)/)
return match ? match[1] : null
}
function getEmbedUrl(url) {
const ytId = getYoutubeId(url)
if (ytId)
return `https://www.youtube.com/embed/${ytId}`
const vimeoId = getVimeoId(url)
if (vimeoId)
return `https://player.vimeo.com/video/${vimeoId}`
return null
}