Skip to content

Instantly share code, notes, and snippets.

@mattkenefick
Last active July 29, 2021 23:54
Show Gist options
  • Save mattkenefick/ce6e370ace8b16148a9ae43c3b03d184 to your computer and use it in GitHub Desktop.
Save mattkenefick/ce6e370ace8b16148a9ae43c3b03d184 to your computer and use it in GitHub Desktop.
Snippet in TypeScript: Extract YouTube ID with Regular Expressions
/**
* Check URL against Regular Expression
*
* @param string url
* @return string|boolean
*/
function parseYoutubeId(url: string): string|boolean {
const regexp: RegExp = new RegExp('(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/\s]{11})', 'i');
const matches: string[] = url.match(regexp);
return matches ? matches[1] : false;
}
/**
* Test a URL against our regular expression
*
* @param string url
* @return void
*/
function test(url: string): void {
const result: string = parseYoutubeId(url);
console.log(result);
}
// Run tests
// -------------------------------------------------------------------
test('https://www.youtube.com/watch?v=yrkfkwzChoM');
test('https://youtube.com/embed/yrkfkwzChoM');
test('This will not match');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment