Skip to content

Instantly share code, notes, and snippets.

@linglung
Forked from Zaggen/getYoutubeId.coffee
Created January 16, 2017 01:57
Show Gist options
  • Select an option

  • Save linglung/0a640079b33201e78fb9f4a1e773839c to your computer and use it in GitHub Desktop.

Select an option

Save linglung/0a640079b33201e78fb9f4a1e773839c 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