Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

getYouTubeThumbnail function not returning the correct thumbnail URL?

I wrote a function to extract the video ID from a YouTube URL and return the corresponding thumbnail image URL. However, the function doesn’t seem to be working as expected.

const getYouTubeThumbnail = (url: string) => {
  const videoId = url.split("v=")[1];
  return https://img.youtube.com/vi/${videoId}/hqdefault.jpg;
};

When I pass a YouTube video URL like https://www.youtube.com/watch?v=-jz8mrwU_Fc&ab_channel=10Alytics, I expect to get https://img.youtube.com/vi/dQw4w9WgXcQ/hqdefault.jpg, but instead, it seems to either not work or return an incorrect URL.

What am I doing wrong? Is there a better way to extract the video ID?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

the function above but it doesn’t work as intended

>Solution :

Your getYouTubeThumbnail function works as intended with regular youtube links, however it may run into problems when extra params are added after the videoID.

Using url.split("v=")[1] retrieves the portion of the URL that comes after "v=".

const getYouTubeThumbnail = (url: string) => {
  const videoId = url.split("v=")[1]?.split("&")[0]; // Gets the part after "v=" and splits by "&" to remove additional parameters
  return `https://img.youtube.com/vi/${videoId}/hqdefault.jpg`;
};

by applying .split("&")[0], it separates any additional parameters that may follow the video ID and captures only the first segment, ensuring that you obtain just the video ID.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading