Jump to content

Module:YouTube

From Swarthmore Knowledge Base

Module:YouTube provides utility functions for parsing YouTube URLs and extracting video IDs. It accepts all common YouTube URL formats, including standard watch URLs (youtube.com/watch?v=), short URLs (youtu.be/), embed URLs (youtube.com/embed/), Shorts URLs (youtube.com/shorts/), and bare video IDs.

Usage

{{#invoke:YouTube|getVideoId|URL}}

Example

{{#invoke:YouTube|getVideoId|https://www.youtube.com/watch?v=dQw4w9WgXcQ}}

Returns: dQw4w9WgXcQ

See also

  • Widget:YouTube — embeds a YouTube video using an ID returned by this module
  • Extension:Scribunto — required for Lua modules



local p = {}

function p.getVideoId(frame)
    local url = frame.args[1] or frame.args["url"] or ""
    return p._getVideoId(url)
end

function p._getVideoId(url)
    url = url:match("^%s*(.-)%s*$")  -- trim whitespace

    -- youtu.be/VIDEO_ID
    local id = url:match("youtu%.be/([%w_%-]+)")
    if id then return id end

    -- youtube.com/watch?v=VIDEO_ID
    id = url:match("[?&]v=([%w_%-]+)")
    if id then return id end

    -- youtube.com/embed/VIDEO_ID
    id = url:match("/embed/([%w_%-]+)")
    if id then return id end

    -- youtube.com/shorts/VIDEO_ID
    id = url:match("/shorts/([%w_%-]+)")
    if id then return id end

    -- bare ID (11 chars, alphanumeric + _ -)
    if url:match("^[%w_%-]+$") and #url == 11 then
        return url
    end

    return nil
end

return p