Next.js | Youtube 영상 가져오기

Lumpen·2024년 10월 10일

Next.js

목록 보기
5/10

Youtube 영상은 사용가 보는 주소를 그대로 가져오면 영상을 읽어오지 못한다

"https://www.youtube.com/watch?v=????" 형태로 된 주소를
"http://www.youtube.com/embed/????" 형태로 바꿔주면 된다

function extractVideoID(url: string) {
  const regExp =
        /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#\&\?]*).*/;
  const match = url.match(regExp);
  if (match && match[7].length == 11) return match[7];
  else return null;
}

const handleAddButtonClick = () => {
    const videoId = extractVideoID(videoUrl);
    setIframeUrl(
      videoId ? `https://www.youtube.com/embed/${videoId}` : videoUrl,
    );
};

정규 표현식 너무 어렵다..

profile
암흑개발자

0개의 댓글