Skip to content

Instantly share code, notes, and snippets.

@Zaggen
Last active January 16, 2017 01:57
Show Gist options
  • Save Zaggen/886e45e96c1a09c58d6e to your computer and use it in GitHub Desktop.
Save Zaggen/886e45e96c1a09c58d6e to your computer and use it in GitHub Desktop.
Youtube id regex matcher
getYoutubeId = (url)->
regExp = ///
^(?:https?:\/\/)? # Optionally checks if the string starts with http:// or https://
(?:www\.)? # Optionally checks if the string has a www. (after the http, https or starts with it)
youtu\.?be(?:\.com)? # Matches the youtube domain, which could be youtube.com or youtu.be
\/(?:v\/|.*u\/\w\/|embed\/|watch\?v=)? # Matches the url paths that could go before the id, like /embed/ or /watch?v=
([^#\&\?]*) # (CAPTURING-GROUP) Matches any id-like string
# Now if the pattern before did not find anything, we try the one below
|^([0-9,a-zA-Z\-]+)$ # (CAPTURING-GROUP) Matches any id-like string, so passing only the id will return it back
///i
match = url.match(regExp)
if match
match[1] or match[2]
else
'error'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment