Apps Artificial Intelligence CSS DevOps Go JavaScript Laravel Linux MongoDB MySQL PHP Python Rust Svelte Vue

Extract a YouTube Video ID from a URL with JavaScript

1 min read .
Extract a YouTube Video ID from a URL with JavaScript

YouTube links appear in several common formats, including youtube.com/watch?v=..., youtu.be/..., Shorts URLs, and embed URLs. A small JavaScript helper can normalize those formats and return the video ID.

Use the URL API

function getYouTubeVideoId(input) {
  const url = new URL(input);

  if (url.hostname === 'youtu.be') {
    return url.pathname.slice(1).split('/')[0] || null;
  }

  if (url.hostname.endsWith('youtube.com')) {
    if (url.pathname === '/watch') {
      return url.searchParams.get('v');
    }

    const match = url.pathname.match(/^\/(?:embed|shorts|live)\/([^/?]+)/);
    return match?.[1] ?? null;
  }

  return null;
}

Examples

console.log(getYouTubeVideoId('https://www.youtube.com/watch?v=QOM0xWASUwE'));
console.log(getYouTubeVideoId('https://youtu.be/QOM0xWASUwE'));
console.log(getYouTubeVideoId('https://www.youtube.com/embed/QOM0xWASUwE'));
console.log(getYouTubeVideoId('https://www.youtube.com/shorts/QOM0xWASUwE'));

Each returns:

QOM0xWASUwE

Handle Invalid Input

new URL() throws for malformed URLs, so wrap the helper when input comes directly from users:

function safeGetYouTubeVideoId(input) {
  try {
    return getYouTubeVideoId(input);
  } catch {
    return null;
  }
}

Why Prefer URL over One Large Regex?

The built-in URL API separates the hostname, path, and query parameters for you. That makes the supported formats explicit and avoids accidentally extracting an ID from an unrelated domain that merely contains a similar-looking string.

Conclusion

Use the URL API to parse YouTube links and handle each supported URL shape deliberately. The result is easier to maintain than a single opaque regular expression and can be extended when new YouTube URL formats matter to your application.

Related Posts

chevron-up