22 lines
619 B
TypeScript
22 lines
619 B
TypeScript
|
|
export function toEmbedUrl(url: string): string {
|
|
let videoId = '';
|
|
|
|
// watch?v=...
|
|
if (url.includes('watch?v=')) {
|
|
const params = new URL(url).searchParams;
|
|
videoId = params.get('v') || '';
|
|
}
|
|
// youtu.be/...
|
|
else if (url.includes('youtu.be/')) {
|
|
const pathname = new URL(url).pathname; // /videoId
|
|
videoId = pathname.split('/')[1] || '';
|
|
}
|
|
// shorts/...
|
|
else if (url.includes('youtube.com/shorts/')) {
|
|
const pathname = new URL(url).pathname; // /shorts/videoId
|
|
videoId = pathname.split('/')[2] || '';
|
|
}
|
|
|
|
return videoId ? `https://www.youtube.com/embed/${videoId}` : '';
|
|
} |