Last active
July 29, 2021 23:54
-
-
Save mattkenefick/ce6e370ace8b16148a9ae43c3b03d184 to your computer and use it in GitHub Desktop.
Snippet in TypeScript: Extract YouTube ID with Regular Expressions
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
/** | |
* 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