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;
};