How to Get Youtube Video id From Url Using JavaScript, HTML and CSS?

Extract a YouTube video ID from a given URL using JavaScript, HTML, and CSS, follow this simple implementation.

Features:

Supports various YouTube URL formats:

-> `https://www.youtube.com/watch?v=VIDEO_ID`
-> `https://youtu.be/VIDEO_ID`
-> `https://www.youtube.com/embed/VIDEO_ID`
-> `https://www.youtube.com/shorts/VIDEO_ID`
-> `https://m.youtube.com/watch?v=VIDEO_ID`

Full Code Implementation Using JavaScript, HTML & CSS:-


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>YouTube Video ID Extractor</title>

<style>
body {
font-family: Arial, sans-serif;
text-align: center;
margin: 50px;
background-color: #f4f4f4;
}
input, button {
padding: 10px;
margin: 10px;
width: 80%;
max-width: 400px;
border-radius: 5px;
border: 1px solid #ccc;
}
button {
background-color: #ff0000;
color: white;
cursor: pointer;
border: none;
}
button:hover {
background-color: #cc0000;
}
#result {
font-weight: bold;
color: green;
margin-top: 20px;
}
</style>

</head>
<body>
<h2>YouTube Video ID Extractor</h2>
<input type="text" id="youtubeUrl" placeholder="Enter YouTube URL">
<button onclick="extractVideoID()">Get Video ID</button>
<p id="result"></p>

<script>
function extractVideoID() {
let url = document.getElementById("youtubeUrl").value;
let videoID = getYouTubeVideoID(url);
if (videoID) {
document.getElementById("result").innerHTML = "Video ID: <strong>" + videoID + "</strong>";
} else {
document.getElementById("result").innerHTML = "Invalid YouTube URL!";
}
}
function getYouTubeVideoID(url) {
let regex = /(?:youtube\.com\/(?:[^\/]+\/.+\/|(?:v|e(?:mbed)?)\/|.*[?&]v=)|youtu\.be\/|youtube\.com\/shorts\/)([^"&?\/\s]{11})/;
let match = url.match(regex);
return match ? match[1] : null;
}
</script>

</body>
</html>

How It Works?

1. User enters a YouTube URL in the input field.
2. When the “Get Video ID” button is clicked:
– The `getYouTubeVideoID()` function extracts the video ID using a regular expression.
– If a match is found, it displays the 11-character video ID.
– Otherwise, it shows “Invalid YouTube URL!”.

This method works with all common YouTube URL formats.

Example:

If the user inputs the URL https://www.youtube.com/watch?v=dQw4w9WgXcQ, the output will be.

Video ID: dQw4w9WgXcQ

This is a simple and effective way to extract the YouTube video ID from a URL using JavaScript, HTML, and CSS.

YouTube Video ID Working Code HTML, CSS Using JavaScript