Sometimes, we want to convert a YouTube video URL to embed code with JavaScript.
In this article, we’ll look at how to convert a YouTube video URL to embed code with JavaScript.
How to convert a YouTube video URL to embed code with JavaScript?
To convert a YouTube video URL to embed code with JavaScript, we manipulate the URL to convert it to the video embed URL.
For instance, we write
const str = "https://www.youtube.com/watch?v=1adfD9";
const res = str.split("=");
const embeddedUrl = "https://www.youtube.com/embed/" + res[1];
document.getElementById("demo").src = res;
to get the embeddedUrl
by getting the video ID with
const res = str.split("=");
and then use res[1]
.
Then we get the embeddedUrl
with
const embeddedUrl = "https://www.youtube.com/embed/" + res[1];
Then we put it in an iframe element by setting its src
property to the video embed URL.
Conclusion
To convert a YouTube video URL to embed code with JavaScript, we manipulate the URL to convert it to the video embed URL.