Convert a youtube video url to embed code

To anyone looking at this in 2020, you can get the embed code by using the oembed API. The reason is that there may be multiple variants of the youtube URL and using regEx may not be an optimal solution.

https://www.youtube.com/oembed?url=<URL>&format=<FORMAT>

example:

https://www.youtube.com/oembed?url=https://www.youtube.com/watch?v=gBrmnB5aOSI&format=json

The response you will get is

{
"type": "video",
"thumbnail_width": 480,
"provider_name": "YouTube",
"title": "Intro To Live Streaming on YouTube",
"thumbnail_height": 360,
"provider_url": "https://www.youtube.com/",
"version": "1.0",
"height": 270,
"author_name": "YouTube Creators",
"html": "<iframe width=\"480\" height=\"270\" src=\"https://www.youtube.com/embed/gBrmnB5aOSI?feature=oembed\" frameborder=\"0\" allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture\" allowfullscreen></iframe>",
"author_url": "https://www.youtube.com/user/creatoracademy",
"width": 480,
"thumbnail_url": "https://i.ytimg.com/vi/gBrmnB5aOSI/hqdefault.jpg"
}

you can use the html data for the iframe


I am late to respond but here what I used to convert the youTube url to Embed and make the video work.

<script>
    function myFunction() {
        var str = "https://www.youtube.com/watch?v=1adfD9";
        var res = str.split("=");
        var embeddedUrl = "https://www.youtube.com/embed/"+res[1];
        document.getElementById("demo").innerHTML = res;
    }
</script>

I hope this helps


I'd be inclined to simply grab the video ID per this question and use it to formulate your embed markup as you like.

http://jsfiddle.net/isherwood/cH6e8/

function getId(url) {
    const regExp = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|&v=)([^#&?]*).*/;
    const match = url.match(regExp);

    return (match && match[2].length === 11)
      ? match[2]
      : null;
}
    
const videoId = getId('http://www.youtube.com/watch?v=zbYf5_S7oJo');
const iframeMarkup = '<iframe width="560" height="315" src="//www.youtube.com/embed/' 
    + videoId + '" frameborder="0" allowfullscreen></iframe>';

console.log('Video ID:', videoId)

Here's a more elaborate demo.