79225917

Date: 2024-11-26 08:45:26
Score: 2
Natty:
Report link

Here is a typescript version of the function that works with multiple versions of YouTube video url:

export const youtubeUrlToEmbed = (urlString: string | undefined | null): string | null | undefined => {
    const template = (v: string) => `https://www.youtube.com/embed/${v}`;
    if (urlString) {
        const url = new URL(urlString);
        if (url.hostname === 'www.youtu.be' || url.hostname === 'youtu.be') {
            return template(url.pathname.substring(1));
        }
        const v = url.searchParams.get('v');
        if ((url.hostname === 'www.youtube.com' || url.hostname === 'youtube.com') && v) {
            return template(v);
        }
    }
    return urlString;
};
Reasons:
  • Blacklisted phrase (1): youtu.be
  • Blacklisted phrase (1): youtube.com
  • Long answer (-0.5):
  • Has code block (-0.5):
  • Low reputation (1):
Posted by: jhrom