Skip to content

Instantly share code, notes, and snippets.

@maggiben
Created December 5, 2021 13:41
Show Gist options
  • Save maggiben/1532e2830d77641e5c7e9c49e51e6092 to your computer and use it in GitHub Desktop.
Save maggiben/1532e2830d77641e5c7e9c49e51e6092 to your computer and use it in GitHub Desktop.
Youtube RexExp utilities
const playlistId = new RegExp(/(?:http|https|)(?::\/\/|)(?:www.|)(?:youtu\.be\/|youtube\.com(?:\/embed\/|\/v\/|\/watch\?v=|\/ytscreeningroom\?v=|\/feeds\/api\/videos\/|\/user\S*[^\w\-\s]|\S*[^\w\-\s]))([\w\-]{12,})[a-z0-9;:@#?&%=+\/\$_.-]*/)
const videoId = new RegExp(/(?:http|https|)(?::\/\/|)(?:www.|)(?:youtu\.be\/|youtube\.com(?:\/embed\/|\/v\/|\/watch\?v=|\/ytscreeningroom\?v=|\/feeds\/api\/videos\/|\/user\S*[^\w\-\s]|\S*[^\w\-\s]))([\w\-]{11})[a-z0-9;:@#?&%=+\/\$_.-]*/)
const getYouTubeId = (youTubeUrl: string): string | undefined => {
const regExp = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=)([^#\&\?]*).*/
var match = youTubeUrl.match(regExp)
if (match && match[2].length == 11) {
return match[2]
}
return undefined
}
export function getYoutubeVideoId(url: string): string | undefined {
const regExp = new RegExp(
/(?:http|https|)(?::\/\/|)(?:www.|)(?:youtu\.be\/|youtube\.com(?:\/embed\/|\/v\/|\/watch\?v=|\/ytscreeningroom\?v=|\/feeds\/api\/videos\/|\/user\S*[^\w\-\s]|\S*[^\w\-\s]))([\w\-]{11})[a-z0-9;:@#?&%=+\/\$_.-]*/
);
const match = url.match(regExp);
if (match && match[1]) {
return match[1];
}
}
/**
* Get playlist id from url
*
* @param {string} url the youtube url
* @returns {string|undefined} the playlist id
*/
export function getYoutubePlaylistId(url: string): string | undefined {
const regExp = new RegExp(
/(?:http|https|)(?::\/\/|)(?:www.|)(?:youtu\.be\/|youtube\.com(?:\/embed\/|\/v\/|\/watch\?v=|\/ytscreeningroom\?v=|\/feeds\/api\/videos\/|\/user\S*[^\w\-\s]|\S*[^\w\-\s]))([\w\-]{12,})[a-z0-9;:@#?&%=+\/\$_.-]*/
);
if (url.includes('list=')) {
const match = url.match(regExp);
if (match && match[1]) {
return match[1];
}
}
return;
}
export const getEmbedUrl = (youTubeUrl: string | null | undefined): string | undefined => {
if (youTubeUrl) {
const videoId = getYouTubeId(youTubeUrl);
if (videoId) {
return `https://www.youtube.com/embed/${videoId}`
}
}
return undefined;
}
@maggiben
Copy link
Author

maggiben commented Dec 5, 2021

Original source from php code here

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment