Skip to content

Instantly share code, notes, and snippets.

@ahallora
Last active February 17, 2021 14:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ahallora/e3f0e305f190f82cbf801338dae14d27 to your computer and use it in GitHub Desktop.
Save ahallora/e3f0e305f190f82cbf801338dae14d27 to your computer and use it in GitHub Desktop.
Extract video ID and host name from Youtube URL

Extract video ID and host name from Youtube URL

A regular expression to extract video ID and host name from a wide range of different youtube links. Built upon this foundation.

^(?:https?:\/\/)?(?:www\.)?(?:m\.)?((youtu\.be|youtube\.com)(?:\/embed\/watch\\?.+|\/watch\?v=|watch\?.+&v=|.))([\w-]{11})(?:.+)?$

Supported URLs

const items = `http://youtube.com/watch?v=iwGFalTRHDA
http://www.youtube.com/watch?v=iwGFalTRHDA&feature=related
https://youtube.com/iwGFalTRHDA
http://youtu.be/n17B_uFF4cA
youtube.com/iwGFalTRHDA
youtube.com/n17B_uFF4cA
http://www.youtube.com/embed/watch?feature=player_embedded&v=r5nB9u4jjy4
http://www.youtube.com/embed/watch?v=r5nB9u4jjy4
http://www.youtube.com/watch?v=t-ZRX8984sc
http://youtu.be/t-ZRX8984sc
https://www.youtube.com/channel/UCDZkgJZDyUnqwB070OyP72g
https://youtube.com/channel/UCDZkgJZDyUnqwB070OyP72g
http://www.vimeo.com/t-ZRX8984sc
https://vimeo.com/?v=1234567890`.split("\n");
const getHostAndId = (url: string) => {
const hostNames = ["youtu.be", "youtube.com"];
const regExpHosts = hostNames
.map((host) => host.replace(".", "\\."))
.join("|");
var regExp = new RegExp(
"^(?:https?:\\/\\/)?(?:www\\.)?(?:m\\.)?((" +
regExpHosts +
")(?:\\/embed\\/watch\\?.+|\\/watch\\?v=|watch\\?.+&v=|.))([\\w-]{11})(?:.+)?$",
"i"
);
var match = url.match(regExp);
const videoId = match && match[3].length == 11 ? match[3] : null;
const host = match ? match[2] : "";
const isValid = hostNames.includes(host) && videoId;
console.log({ videoId, host, isValid });
return isValid ? { host, videoId } : null;
};
console.table(
items.map(item => ({
item,
...getHostAndId(item)
}))
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment