Carlos Veloz
Carlos Veloz

Reputation: 53

Embed Youtube video from URL

Im new in all this amazing thing called front end and i´m already working in a project but i need a little help with this:

So the thing is that the user could enter a youtube URL in a text box and a embed iframe video is automatically generated from it so he can preview it without reloading the page

How could i do that?

a have found 2 separated scripts that could help but i can´t make them work at the same time:

Extract YouTube video ID from URL:

[http://codepen.io/catmull/pen/cnpsK][1]

YouTube Embed Optimized with JavaScript:

[http://codepen.io/SitePoint/pen/CKFuh][1]

Any ideas? It will really help me if you answer with a live example :)

Upvotes: 1

Views: 13017

Answers (2)

jhrom
jhrom

Reputation: 3

Here is a typescript version of the function that works with multiple versions of YouTube video url:

export const youtubeUrlToEmbed = (urlString: string | undefined | null): string | null | undefined => {
    const template = (v: string) => `https://www.youtube.com/embed/${v}`;
    if (urlString && URL.canParse(urlString)) {
        const url = new URL(urlString);
        // short URL
        if (url.hostname === 'www.youtu.be' || url.hostname === 'youtu.be') {
            return template(url.pathname.startsWith('/') ? url.pathname.substring(1) : url.pathname);
        }
        // regular URL
        const v = url.searchParams.get('v');
        if ((url.hostname === 'www.youtube.com' || url.hostname === 'youtube.com') && v) {
            return template(v);
        }
    }
    return urlString;
};

Usage:

const first = youtubeUrlToEmbed('https://youtu.be/YD6Dkj3-RSQ?si=C-Dbo4vLWG4GdtWk');
console.log(first); // 'https://www.youtube.com/embed/YD6Dkj3-RSQ'

const second = youtubeUrlToEmbed('https://www.youtube.com/watch?v=YD6Dkj3-RSQ&ab_channel=iVys%C3%ADl%C3%A1n%C3%AD');
console.log(second); // 'https://www.youtube.com/embed/YD6Dkj3-RSQ'

The code above only transforms YouTube links in the regular and short versions to the embed version, otherwise it returns the previous value.

YouTube embed video documentation: here.

Upvotes: 0

Ryan Radomski
Ryan Radomski

Reputation: 101

if you have youtube url https://www.youtube.com/watch?v=sGbxmsDFVnE, you can embed it by taking the video id off the end and putting at the end of youtube.com/embed/

you can get the video id using string.split()

var url = "https://www.youtube.com/watch?v=sGbxmsDFVnE";
var id = url.split("?v=")[1]; //sGbxmsDFVnE

var embedlink = "http://www.youtube.com/embed/" + id; //www.youtube.com/embed/sGbxmsDFVnE

then just make that embed link the source to an existing iframe on the page

document.getElementById("myIframe").src = embedLink;

example of an iframe

<iframe id="myIframe" width="560" height="315" frameborder="0" allowfullscreen></iframe>

working code here

Upvotes: 7

Related Questions