테스트 사이트 - 개발 중인 베타 버전입니다

유튜브 링크 표현

이 코드를view.skin.php에 추가하세요

[code]<script>

// bo_v_con 요소 선택

const boVCon = document.getElementById('bo_v_con');

 

// 유튜브 링크 형식 정의

const youtubeDomains = [

  'youtube.com',

  'youtu.be',

  'www.youtube.com'

];

 

// 정규 표현식 생성

const youtubeRegex = new RegExp(`(https?://)?(${youtubeDomains.join('|')})/(shorts/|watch\\?v=|)([\\w-]+)`, 'g');

 

// bo_v_con의 텍스트를 가져와서 링크를 검색

let textContent = boVCon.innerHTML;

 

// 링크가 발견되면 object 요소를 생성

const matches = textContent.match(youtubeRegex);

if (matches) {

  // 중복 제거를 위한 Set 사용

  const uniqueLinks = Array.from(new Set(matches));

 

  uniqueLinks.forEach(link => {

    let videoId = '';

 

    // 링크에 따라 videoId를 추출

    if (link.includes('youtu.be')) {

      videoId = link.split('/').pop(); // youtu.be 링크에서 videoId 추출

    } else if (link.includes('youtube.com')) {

      const url = new URL(link);

      if (url.pathname.includes('shorts')) {

        videoId = url.pathname.split('/').pop(); // shorts 링크에서 videoId 추출

      } else if (url.searchParams.has('v')) {

        videoId = url.searchParams.get('v'); // watch?v= 링크에서 videoId 추출

      } else {

        videoId = url.pathname.split('/').pop(); // 기본 링크에서 videoId 추출

      }

    }

 

    // videoId가 유효한 경우에만 iframe 요소 생성

    if (videoId) {

      // iframe 요소 생성

      const videoContainer = `<div class="video-container" style="text-align: center;">

                                <iframe width="100%" height="500" src="https://www.youtube.com/embed/${videoId}" allowfullscreen></iframe>

                              </div>`;

 

      // 기존 콘텐츠에서 해당 링크를 비디오 요소로 교체

      const safeLink = link.replace(/[-\/\\^$.*+?()[\]{}|]/g, '\\$&'); // 링크를 안전하게 변환

      textContent = textContent.replace(new RegExp(`(?:<a[^>]*>)?${safeLink}(?:<\/a>)?`, 'g'), videoContainer); // 링크를 videoContainer로 교체

    }

  });

 

  // bo_v_con의 내용을 업데이트

  boVCon.innerHTML = textContent; // 업데이트된 내용을 bovcon에 설정

}

</script>[/code]

 

참고자료: http://1004web.kr/board_ujsG12/96855

뤼튼이 다 떠먹여줬습니다 :)

댓글 작성

댓글을 작성하시려면 로그인이 필요합니다.

로그인하기

게시판 목록

그누보드5 팁자료실

글쓰기