Created
December 5, 2021 13:41
-
-
Save maggiben/1532e2830d77641e5c7e9c49e51e6092 to your computer and use it in GitHub Desktop.
Youtube RexExp utilities
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
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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Original source from
php
code here