You can use JavaScript to extract the video ID from the URL and then insert the corresponding YouTube iframe embed code into the DOM.
Steps:
1. HTML Structure
<input type="text" id="youtube-url" placeholder="Enter YouTube URL">
<button id="load-video">Load Video</button>
<div id="video-container"></div>
2. JavaScript to Handle URL Input and Embed Video
document.getElementById('load-video').addEventListener('click', function () {
const youtubeUrl = document.getElementById('youtube-url').value;
const videoId = extractVideoId(youtubeUrl);
if (videoId) {
const embedCode = `<iframe width="560" height="315" src="https://www.youtube.com/embed/${videoId}" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>`;
document.getElementById('video-container').innerHTML = embedCode;
} else {
alert('Invalid YouTube URL');
}
});
function extractVideoId(url) {
// Regex to extract video ID from various YouTube URL formats
const regex = /(?:https?:\/\/)?(?:www\.)?(?:youtube\.com\/(?:[^\/\n\s]+\/\S+\/|(?:v|e(?:mbed)?)\/|\S*?[?&]v=)|(?:youtu\.be\/)([a-zA-Z0-9_-]{11})/;
const match = url.match(regex);
return match ? match[1] : null;
}