youtube.ts 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. /**
  2. * YouTube URL에서 video ID 추출 (watch?v=, youtu.be/, /embed/, /shorts/ 지원).
  3. */
  4. export function youTubeId(url: string|null|undefined): string|null {
  5. if (!url) {
  6. return null;
  7. }
  8. try {
  9. const u = new URL(url);
  10. let id = '';
  11. if (u.hostname.includes('youtu.be')) {
  12. id = u.pathname.slice(1);
  13. } else if (u.searchParams.get('v')) {
  14. id = u.searchParams.get('v') ?? '';
  15. } else if (u.pathname.includes('/embed/')) {
  16. id = u.pathname.split('/embed/')[1] ?? '';
  17. } else if (u.pathname.includes('/shorts/')) {
  18. id = u.pathname.split('/shorts/')[1] ?? '';
  19. }
  20. id = id.split('/')[0].split('?')[0];
  21. return id || null;
  22. } catch {
  23. return null;
  24. }
  25. }
  26. /**
  27. * YouTube embed URL (`https://www.youtube.com/embed/<id>`).
  28. */
  29. export function youTubeEmbedUrl(url: string|null|undefined): string|null {
  30. const id = youTubeId(url);
  31. return id ? `https://www.youtube.com/embed/${id}` : null;
  32. }
  33. /**
  34. * YouTube 썸네일 URL (`https://img.youtube.com/vi/<id>/hqdefault.jpg`).
  35. */
  36. export function youTubeThumbnail(url: string|null|undefined): string|null {
  37. const id = youTubeId(url);
  38. return id ? `https://img.youtube.com/vi/${id}/hqdefault.jpg` : null;
  39. }