Converting youtube video link to embed link with JavaScript

Videos on youtube usually have a URI such as the following:

http://www.youtube.com/watch?v=nCgQDjiotG0

These URIs cannot be used to embed the video in an iframe such as the following:

In order to work as part of an embedded iframe, youtube video links must be in the following format:

http://www.youtube.com/embed/nCgQDjiotG0

Luckily, given any ‘normal’ youtube link, it is very easy to generate such an embed link. In JavaScript, this can be done with the following function:

function createYouTubeEmbedLink (link) {
 return link.replace("http://www.youtube.com/watch?v=", "http://www.youtube.com/embed/");
 }

6 thoughts on “Converting youtube video link to embed link with JavaScript

  1. A really old and slow, computer illiterate person like me cannot follow technical language readily taken for granted by those in the ‘know. I would love to have step by step instructions to link a YouTube video to one word in my comment to someone else’s blog.
    When you posted:
    “Luckily, given any ‘normal’ youtube link, it is very easy to generate such an embed link. In JavaScript, this can be done with the following function:

    1
    function createYouTubeEmbedLink (link) {
    2
    return link.replace(“http://www.youtube.com/watch?v=”, “http://www.youtube.com/embed/”);
    3
    }

    I haven’t a clue what you are talking about. I know how to copy the YouTube URL but how do I go to JavaScript (?) in order to complete the following steps of your instructions?

  2. Now how can i use this code to replace src attribute inside iframe? I pasted javascript code but now working.
    This is my iframe code

    But is not been replaced to

    Any solution?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s