PaulBratslavsky / epic-next-course

57 stars 10 forks source link

extractYouTubeID() doesn't work on shareable links. #2

Open briankjkim opened 2 months ago

briankjkim commented 2 months ago

Hello all! 🖐️

As I follow the tutorial myself and test the application, I've come to realize that the current extractYouTubeID() doesn't process mobile or shareable YouTube links.

Example of working URL: https://www.youtube.com/watch?v=FTH6Dn3AyIQ

Example of currently invalid URL: https://youtu.be/FTH6Dn3AyIQ?si=M2pFsifdk3EMI6II

Here is the current implementation of extractYouTubeID()

export function extractYouTubeID(urlOrID: string): string | null {
  // Regular expression for YouTube ID format
  const regExpID = /^[a-zA-Z0-9_-]{11}$/;

  // Check if the input is a YouTube ID
  if (regExpID.test(urlOrID)) {
    return urlOrID;
  }

  // Regular expression for standard YouTube links
  const regExpStandard = /youtube\.com\/watch\?v=([a-zA-Z0-9_-]+)/;

  // Regular expression for YouTube Shorts links
  const regExpShorts = /youtube\.com\/shorts\/([a-zA-Z0-9_-]+)/;

  // Check for standard YouTube link
  const matchStandard = urlOrID.match(regExpStandard);
  if (matchStandard) {
    return matchStandard[1];
  }

  // Check for YouTube Shorts link
  const matchShorts = urlOrID.match(regExpShorts);
  if (matchShorts) {
    return matchShorts[1];
  }

  // Return null if no match is found
  return null;
}

To solve the issue, I've made the following changes to my code:

  // Regular expression for standard YouTube links
  const regExpStandard =
    /(?:youtube\.com\/(?:watch\?v=|v\/)|youtu\.be\/|youtube\.com\/embed\/)([a-zA-Z0-9_-]+)/;

Hope anyone had a similar issue! I've attached the screenshot images for demonstration.

okurl working shareableurl invalid

PaulBratslavsky commented 2 months ago

@briankjkim awesome, thank you for the update. I will make the change in the blog post to reflect the new regex.