10

Say there is a div that has content and a youtube link. I want to grab that youtube link and embed it.

<div id="content"><p>Here is a cool video.  Check it out: http://www.youtube.com/watch?v=oHg5SJYRHA0</p></div>

I want to grab the link and replace it with the embed code with js (jquery).

Update 1:

This is my js so far:

    $("#content").each(function(){
    var allContent = $(this).html();
    //need regex to find all links with youtube in it, ovbiously it can't == youtube.com, but basically the link has to have youtube.com in it.
    if ($("a",allContent).attr("href") == "youtube.com" ) {
        // grab youtube video id
        /* replace link with <div id="yt-video">
        <object width="560" height="340"><param name="movie" value="http://www.youtube.com/v/429l13dS6kQ&hl=en&fs=1&"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/429l13dS6kQ&hl=en&fs=1&" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="560" height="340"></embed></object>
        </div>
        */
    }
});
2

3 Answers 3

16

I changed the content from an id to a class because I was guessing you'd have more than one content area?

I'm sure there is a much more efficient way to do this, but this is my attempt at it. Note I suck at regex, so what I have is as close as I can get, I'm sure someone can help improve it, so it doesn't have to replace the ?v= inside the each loop.

HTML

<div class="content"><p>Here is a cool video.  Check it out: http://www.youtube.com/watch?v=oHg5SJYRHA0 and this one http://www.youtube.com/watch?v=fLBPsZVI8Gc&feature=player_embedded</p></div>
<div class="content"><p>Here is a cool video.  Check it out: http://www.youtube.com/watch?v=fLBPsZVI8Gc&feature=player_embedded</p></div>

Script

$(document).ready(function(){
 // I added the video size here in case you wanted to modify it more easily
 var vidWidth = 425;
 var vidHeight = 344;

 $('.content:contains("youtube.com/watch")').each(function(){
  var that = $(this);
  var txt = $(this).html();
  // Tthis could be done by creating an object, adding attributes & inserting parameters, but this is quicker
  var e1 = '<obj'+'ect width="' + vidWidth + '" height="' + vidHeight + '"><param name="movie" value="http://www.youtube.com/v/';
  var e2 = '&hl=en&fs=1"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" ' +
   'value="always"></param><em'+'bed src="http://www.youtube.com/v/';
  var e3 = '&hl=en&fs=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="' + vidWidth +
   '" ' + 'height="' + vidHeight + '"></embed></object> ';

  var vid = txt.match(/((\?v=)(\w[\w|-]*))/g); // end up with ?v=oHg5SJYRHA0
  if (vid.length) {
   $.each(vid, function(i){
    var ytid = this.replace(/\?v=/,'') // end up with oHg5SJYRHA0
    that.append( e1 + ytid + e2 + ytid + e3 ) 
   })
  }
 })
})

I'll be the first to admit it's not pretty, but it works. I also pasted a working version of this code in this pastebin


Update: I've cleaned up the code a bit, here is how it looks now (demo):

$(document).ready(function(){
 // I added the video size here in case you wanted to modify it more easily
 var vidWidth = 425;
 var vidHeight = 344;

 var obj = '<object width="' + vidWidth + '" height="' + vidHeight + '">' +
     '<param name="movie" value="http://www.youtube.com/v/[vid]&hl=en&fs=1">' +
     '</param><param name="allowFullScreen" value="true"></param><param ' +
     'name="allowscriptaccess" value="always"></param><em' +
     'bed src="http://www.youtube.com/v/[vid]&hl=en&fs=1" ' +
     'type="application/x-shockwave-flash" allowscriptaccess="always" ' +
     'allowfullscreen="true" width="' + vidWidth + '" ' + 'height="' +
     vidHeight + '"></embed></object> ';

 $('.content:contains("youtube.com/watch")').each(function(){
  var that = $(this);
  var vid = that.html().match(/(?:v=)([\w\-]+)/g); // end up with v=oHg5SJYRHA0
  if (vid.length) {
   $.each(vid, function(){
    that.append( obj.replace(/\[vid\]/g, this.replace('v=','')) );
   });
  }
 });
});
Sign up to request clarification or add additional context in comments.

5 Comments

Good answer, only change is in my answer below
hi, I want also to remove the youtube link and replace it by the video , how can I do that ?
@Waseem: I updated the demo (jsfiddle.net/9r7pj/20), but I still suck at regex. I added this line that.html(function(i,h){return h.replace(/(http:\/\/www.youtube.com\/watch\?v=\w+((\&\w+=\w+)+)?)/g,'');}); and I tested the regex (rubular.com/r/QiOvgv8stR) and it seemed to work there, but not in jsFiddle... so I have no idea. Either way, you can manually remove the extra parameters from the url if you have to.
@fudgey I modified the regex and it worked fine , check it in jsFiddle here jsfiddle.net/9r7pj/21
@Waseem: I just noticed that youtube provides iframe code by default now. I guess so it'll work with iphones or something. Just a heads up ;)
3

I was on pretty much the same track as fudgey, but I suck a regexps even more than him, so I've "borrowed" his code up until that point. One change I have made is to use swfobject to embed the video rather than handrolling the embed code. It just means you have to add the swfobject library to the page

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/swfobject/2.1/swfobject.js"></script>

HTML is the same as fudgey's

<div class="content"><p>Here is a cool video.  Check it out: http://www.youtube.com/watch?v=oHg5SJYRHA0 and this one http://www.youtube.com/watch?v=fLBPsZVI8Gc&feature=player_embedded</p></div>
<div class="content"><p>Here is a cool video.  Check it out: http://www.youtube.com/watch?v=fLBPsZVI8Gc&feature=player_embedded</p></div>

Small change to the javascript

$(function(){
    // I added the video size here in case you wanted to modify it more easily
    var vidWidth = 425;
    var vidHeight = 344;

    $('.content:contains("youtube.com/watch")').each(function(i){
        var that = $(this);
        var txt = $(this).html();       
        var vid = txt.match(/((\?v=)(\w[\w|-]*))/g); // end up with ?v=oHg5SJYRHA0
            if (vid.length) {
                $.each(vid, function(x){
                    var ytid = this.replace(/\?v=/,'') // end up with oHg5SJYRHA0   
                    var playerid = 'videoplayer_' + i + "_" + x; 
                    that.append("<div id='" + playerid + "'></div>");
                    swfobject.embedSWF("http://www.youtube.com/v/" + ytid, playerid, vidWidth, vidHeight, "8");                     
                })
            }
        })
    })

Kudos to Fudgey's answer tho

1 Comment

Nice! I forgot about using swfobject.js :)
1

You'll need to get the content of the div with something like this:

var text = $("div#content p").html();  // or .text()

With that text, you can use string manipulation or regular expressions to find the url. Then, you can create jquery content to add with:

var content = $('<a href="...">...</a>');

and add it to something with the manipulation methods of jquery, like

var destination = $("body");
destination.append(content);

To get more detail than that, your question will need more details.

1 Comment

I've updated my question with my current js. I added comments to what I need or what I'm stuck on.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.