getYoutubeId

Extract the Youtube ID from a YouYube URL. Returns false if invalid url.

Example

svelte
<script>
  import { getYoutubeId } from '@eirikk/sveltekit-stuff';

  // also supports shorts (https://www.youtube.com/shorts/M1cz-0G1P38)
  // or youtu.be (https://youtu.be/WIRK_pGdIdA)
  export let youtubeUrl = 'https://www.youtube.com/watch?v=WIRK_pGdIdA';
  $: youtubeId = getYoutubeId(youtubeUrl);
  $: src = 'https://www.youtube.com/embed/' + youtubeId;
</script>

<iframe
  {src}
  width="1920"
  height="1080"
  frameborder="0"
  allowfullscreen />

Demo

YouTube ID = WIRK_pGdIdA
NPM version