npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

opex-yt-id

v1.1.0

Published

Extracts YouTube video, channel, and playlist IDs from various URLs

Readme

npm version License: MIT Visitors

Get YouTube ID From URL / Получение ID YouTube из URL

English | Русский


English

A robust Node.js library (ESM) to extract YouTube Video, Channel (UC-prefixed), and Playlist (PL-prefixed) IDs from a wide variety of URL formats.

Features

  • Video IDs:
    • Supports standard youtube.com URLs (/watch, /v/, /embed/, /shorts/, /live/, etc.)
    • Supports mobile m.youtube.com URLs.
    • Supports official shortener youtu.be and alternative y2u.be.
    • Supports privacy-enhanced youtube-nocookie.com embeds.
    • Supports music.youtube.com and kids.youtube.com.
    • Supports image links from i.ytimg.com.
    • Supports legacy formats (/e/, /vi/, user channel fragments #p/u/...).
    • Handles <iframe> embed code strings.
    • Provides a generic fallback for /watch?v={ID} on any domain.
  • Channel IDs (UC-prefixed):
    • Supports standard youtube.com/channel/UC... URLs.
    • Limitation: Does not resolve custom URLs (/c/Name), legacy usernames (/user/Name), or handles (/@Handle) as this requires external lookups.
  • Playlist IDs (PL-prefixed):
    • Supports standard youtube.com/playlist?list=PL... URLs.
    • Supports URLs where a video is watched within a playlist (/watch?v=...&list=PL...).
    • Supports music.youtube.com/playlist?list=PL....
  • General:
    • Supports youtube:// mobile app schemes (common video patterns).
    • Includes support for known third-party frontend domains (like Invidious, Piped - based on static list) for relevant ID types.
    • Written in modern ECMAScript (ESM) with type definitions included.

Installation

npm install opex-yt-id
# or
yarn add opex-yt-id

Usage (ESM)

import {
    getYouTubeVideoId,
    getYouTubeChannelId,
    getYouTubePlaylistId
} from 'opex-yt-id';

// Video Examples
const urlV1 = 'https://www.youtube.com/watch?v=dQw4w9WgXcQ';
const urlV2 = 'https://youtu.be/jNQXAC9IVRw?t=15';
const urlV3 = '<iframe src="https://www.youtube-nocookie.com/embed/abcdefghijk"></iframe>';
const urlV4 = 'https://yewtu.be/watch?v=lmnopqrs_tu'; // Invidious example
const urlV5 = 'https://some-random-proxy.net/watch?v=123456789_A'; // Generic fallback
const urlV6 = 'not a valid url string';

console.log("Video IDs:");
console.log(getYouTubeVideoId(urlV1)); // Output: dQw4w9WgXcQ
console.log(getYouTubeVideoId(urlV2)); // Output: jNQXAC9IVRw
console.log(getYouTubeVideoId(urlV3)); // Output: abcdefghijk
console.log(getYouTubeVideoId(urlV4)); // Output: lmnopqrs_tu
console.log(getYouTubeVideoId(urlV5)); // Output: 123456789_A
console.log(getYouTubeVideoId(urlV6)); // Output: null
console.log(getYouTubeVideoId(null));  // Output: null

// Channel Examples
const urlC1 = 'https://www.youtube.com/channel/UCBR8-60-B28hp2BmDPdntcQ';
const urlC2 = 'https://m.youtube.com/channel/UC_Channel_ID_Chars';
const urlC3 = 'https://youtube.com/c/SomeCustomName'; // Will return null
const urlC4 = 'https://www.youtube.com/@handle'; // Will return null
const urlC5 = 'https://vid.puffyan.us/channel/UCBR8-60-B28hp2BmDPdntcQ'; // 3rd party

console.log("\nChannel IDs (UC-prefixed only):");
console.log(getYouTubeChannelId(urlC1)); // Output: UCBR8-60-B28hp2BmDPdntcQ
console.log(getYouTubeChannelId(urlC2)); // Output: UC_Channel_ID_Chars
console.log(getYouTubeChannelId(urlC3)); // Output: null (custom URL not resolved)
console.log(getYouTubeChannelId(urlC4)); // Output: null (handle not resolved)
console.log(getYouTubeChannelId(urlC5)); // Output: UCBR8-60-B28hp2BmDPdntcQ

// Playlist Examples
const urlP1 = 'https://www.youtube.com/playlist?list=PLBCF2DAC6FFB574DE';
const urlP2 = 'https://www.youtube.com/watch?v=VIDEOID&list=PLIivdWyY5sqL9mXChOLu_U4Q431r9fIGN&index=2';
const urlP3 = 'https://music.youtube.com/playlist?list=PL_Playlist_ID_Chars';

console.log("\nPlaylist IDs (PL-prefixed only):");
console.log(getYouTubePlaylistId(urlP1)); // Output: PLBCF2DAC6FFB574DE
console.log(getYouTubePlaylistId(urlP2)); // Output: PLIivdWyY5sqL9mXChOLu_U4Q431r9fIGN
console.log(getYouTubePlaylistId(urlP3)); // Output: PL_Playlist_ID_Chars

API

getYouTubeVideoId(urlString)

  • urlString: string | null | undefined - The URL or string potentially containing a YouTube video link or ID.
  • Returns: string | null - The 11-character YouTube Video ID if found and valid, otherwise null.

getYouTubeChannelId(urlString)

  • urlString: string | null | undefined - The URL or string potentially containing a YouTube channel link.
  • Returns: string | null - The 24-character YouTube Channel ID (starting with UC) if found and valid, otherwise null.
  • Note: Does not resolve custom URLs (/c/), legacy usernames (/user/), or handles (/@/).

getYouTubePlaylistId(urlString)

  • urlString: string | null | undefined - The URL or string potentially containing a YouTube playlist link.
  • Returns: string | null - The YouTube Playlist ID (starting with PL) if found and valid, otherwise null.

License

MIT


Русский

Надежная Node.js библиотека (ESM) для извлечения ID Видео, Каналов (с префиксом UC) и Плейлистов (с префиксом PL) YouTube из множества различных форматов URL.

Возможности

  • ID Видео:
    • Поддерживает стандартные URL youtube.com (/watch, /v/, /embed/, /shorts/, /live/ и т.д.)
    • Поддерживает мобильные URL m.youtube.com.
    • Поддерживает официальный сокращатель youtu.be и альтернативный y2u.be.
    • Поддерживает встраивания youtube-nocookie.com с повышенной приватностью.
    • Поддерживает music.youtube.com и kids.youtube.com.
    • Поддерживает ссылки на изображения с i.ytimg.com.
    • Поддерживает устаревшие форматы (/e/, /vi/, фрагменты каналов пользователей #p/u/...).
    • Обрабатывает строки с кодом встраивания <iframe>.
    • Предоставляет общий запасной вариант для /watch?v={ID} на любом домене.
  • ID Каналов (с префиксом UC):
    • Поддерживает стандартные URL youtube.com/channel/UC....
    • Ограничение: Не распознает пользовательские URL (/c/Имя), устаревшие имена пользователей (/user/Имя) или дескрипторы (/@Дескриптор), так как это требует внешних запросов.
  • ID Плейлистов (с префиксом PL):
    • Поддерживает стандартные URL youtube.com/playlist?list=PL....
    • Поддерживает URL, где видео просматривается в рамках плейлиста (/watch?v=...&list=PL...).
    • Поддерживает music.youtube.com/playlist?list=PL....
  • Общее:
    • Поддерживает схемы мобильного приложения youtube:// (распространенные шаблоны для видео).
    • Включает поддержку известных сторонних фронтенд-доменов (таких как Invidious, Piped - на основе статического списка) для соответствующих типов ID.
    • Написана на современном ECMAScript (ESM) с включенными определениями типов.

Установка

npm install opex-yt-id
# или
yarn add opex-yt-id

Использование (ESM)

import {
    getYouTubeVideoId,
    getYouTubeChannelId,
    getYouTubePlaylistId
} from 'opex-yt-id';

// Примеры для Видео
const urlV1 = 'https://www.youtube.com/watch?v=dQw4w9WgXcQ';
const urlV2 = 'https://youtu.be/jNQXAC9IVRw?t=15';
const urlV3 = '<iframe src="https://www.youtube-nocookie.com/embed/abcdefghijk"></iframe>';
const urlV4 = 'https://yewtu.be/watch?v=lmnopqrs_tu'; // Пример Invidious
const urlV5 = 'https://some-random-proxy.net/watch?v=123456789_A'; // Общий запасной вариант
const urlV6 = 'невалидная строка url';

console.log("ID Видео:");
console.log(getYouTubeVideoId(urlV1)); // Вывод: dQw4w9WgXcQ
console.log(getYouTubeVideoId(urlV2)); // Вывод: jNQXAC9IVRw
console.log(getYouTubeVideoId(urlV3)); // Вывод: abcdefghijk
console.log(getYouTubeVideoId(urlV4)); // Вывод: lmnopqrs_tu
console.log(getYouTubeVideoId(urlV5)); // Вывод: 123456789_A
console.log(getYouTubeVideoId(urlV6)); // Вывод: null
console.log(getYouTubeVideoId(null));  // Вывод: null

// Примеры для Каналов
const urlC1 = 'https://www.youtube.com/channel/UCBR8-60-B28hp2BmDPdntcQ';
const urlC2 = 'https://m.youtube.com/channel/UC_Channel_ID_Chars';
const urlC3 = 'https://youtube.com/c/SomeCustomName'; // Вернет null
const urlC4 = 'https://www.youtube.com/@handle'; // Вернет null
const urlC5 = 'https://vid.puffyan.us/channel/UCBR8-60-B28hp2BmDPdntcQ'; // Сторонний фронтенд

console.log("\nID Каналов (только с префиксом UC):");
console.log(getYouTubeChannelId(urlC1)); // Вывод: UCBR8-60-B28hp2BmDPdntcQ
console.log(getYouTubeChannelId(urlC2)); // Вывод: UC_Channel_ID_Chars
console.log(getYouTubeChannelId(urlC3)); // Вывод: null (пользовательский URL не распознан)
console.log(getYouTubeChannelId(urlC4)); // Вывод: null (дескриптор не распознан)
console.log(getYouTubeChannelId(urlC5)); // Вывод: UCBR8-60-B28hp2BmDPdntcQ

// Примеры для Плейлистов
const urlP1 = 'https://www.youtube.com/playlist?list=PLBCF2DAC6FFB574DE';
const urlP2 = 'https://www.youtube.com/watch?v=VIDEOID&list=PLIivdWyY5sqL9mXChOLu_U4Q431r9fIGN&index=2';
const urlP3 = 'https://music.youtube.com/playlist?list=PL_Playlist_ID_Chars';

console.log("\nID Плейлистов (только с префиксом PL):");
console.log(getYouTubePlaylistId(urlP1)); // Вывод: PLBCF2DAC6FFB574DE
console.log(getYouTubePlaylistId(urlP2)); // Вывод: PLIivdWyY5sqL9mXChOLu_U4Q431r9fIGN
console.log(getYouTubePlaylistId(urlP3)); // Вывод: PL_Playlist_ID_Chars

API

getYouTubeVideoId(urlString)

  • urlString: string | null | undefined - URL или строка, потенциально содержащая ссылку или ID видео YouTube.
  • Возвращает: string | null - 11-значный ID видео YouTube, если найден и действителен, иначе null.

getYouTubeChannelId(urlString)

  • urlString: string | null | undefined - URL или строка, потенциально содержащая ссылку на канал YouTube.
  • Возвращает: string | null - 24-значный ID канала YouTube (начинающийся с UC), если найден и действителен, иначе null.
  • Примечание: Не распознает пользовательские URL (/c/), устаревшие имена пользователей (/user/) или дескрипторы (/@/).

getYouTubePlaylistId(urlString)

  • urlString: string | null | undefined - URL или строка, потенциально содержащая ссылку на плейлист YouTube.
  • Возвращает: string | null - ID плейлиста YouTube (начинающийся с PL), если найден и действителен, иначе null.

Лицензия

MIT