Skip to content

Instantly share code, notes, and snippets.

@eduardinni
Forked from takien/youtubeID.js
Last active July 31, 2022 12:39
Show Gist options
  • Star 14 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save eduardinni/ff0011ba8c411fa06253c1d5850373cf to your computer and use it in GitHub Desktop.
Save eduardinni/ff0011ba8c411fa06253c1d5850373cf to your computer and use it in GitHub Desktop.
Get YouTube ID from various YouTube URL using Ruby
# Get YouTube ID from various YouTube URL
# Ruby port from JavaScript version: https://gist.github.com/takien/4077195/
def get_youtube_id(url)
id = ''
url = url.gsub(/(>|<)/i,'').split(/(vi\/|v=|\/v\/|youtu\.be\/|\/embed\/)/)
if url[2] != nil
id = url[2].split(/[^0-9a-z_\-]/i)
id = id[0];
else
id = url;
end
id
end
# Tested URLs:
# url = 'http://youtube.googleapis.com/v/4e_kz79tjb8?version=3'
# url = 'https://www.youtube.com/watch?feature=g-vrec&v=Y1xs_xPb46M'
# url = 'http://www.youtube.com/watch?feature=player_embedded&v=Ab25nviakcw#'
# url = 'http://youtu.be/Ab25nviakcw'
# url = 'http://www.youtube.com/watch?v=Ab25nviakcw'
# url = '<iframe width="420" height="315" src="http://www.youtube.com/embed/Ab25nviakcw" frameborder="0" allowfullscreen></iframe>'
# url = '<object width="420" height="315"><param name="movie" value="http://www.youtube-nocookie.com/v/Ab25nviakcw?version=3&amp;hl=en_US"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube-nocookie.com/v/Ab25nviakcw?version=3&amp;hl=en_US" type="application/x-shockwave-flash" width="420" height="315" allowscriptaccess="always" allowfullscreen="true"></embed></object>'
# url = 'http://i1.ytimg.com/vi/Ab25nviakcw/default.jpg'
# url = 'https://www.youtube.com/watch?v=BGL22PTIOAM&feature=g-all-xit'
# url = 'BGL22PTIOAM'
@SpaYco
Copy link

SpaYco commented Jun 7, 2020

this has been really helpful, thank you.

Copy link

ghost commented Feb 28, 2021

It helped me a lot, thank you! I modified it a bit to be more ruby style

  def get_youtube_id(url)
    url = url.gsub(/(>|<)/i, '').split(%r{(vi/|v=|/v/|youtu\.be/|/embed/)})
    return url if url[2].nil?

    id = url[2].split(/[^0-9a-z_\-]/i)
    id[0]
  end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment