使用JS(jQuery)查找所有YouTube链接

10
Great! How may I assist you today?
<div id="content"><p>Here is a cool video.  Check it out: http://www.youtube.com/watch?v=oHg5SJYRHA0</p></div>

我希望使用js(jquery)获取链接并将其替换为嵌入代码。

更新1:

这是我目前的js代码:

    $("#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>
        */
    }
});

1
这个问题的答案可能有助于正则表达式部分:https://dev59.com/AkrSa4cB1Zd3GeqPUkD0 - beggs
顺便提一句,有一个YouTube的JavaScript API,非常容易使用且功能强大(如播放列表等)。https://developers.google.com/youtube/js_api_reference - Matthew Lock
3个回答

16

我将content从id改成class,因为我猜你可能有多个内容区域?

我确信有更有效的方法来做这件事,但这是我的尝试。注意我不擅长正则表达式,所以我尽力了,我相信有人可以帮助改进它,使其无需在each循环内替换?v=

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>

脚本

$(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 ) 
   })
  }
 })
})
我要承认这不是很美观,但它有效。我也在这个pastebin中粘贴了这个代码的可运行版本。
更新:我稍微整理了一下代码,现在它看起来是这样的(演示):
$(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=','')) );
   });
  }
 });
});

好的答案,唯一的变化在下面我的回答中。 - micmcg
嗨,我还想删除 YouTube 链接,并用视频替换它,我该怎么做? - Waseem Senjer
@Waseem:我更新了演示(http://jsfiddle.net/9r7pj/20/),但是我仍然不擅长正则表达式。我添加了这一行代码 that.html(function(i,h){return h.replace(/(http:\/\/www.youtube.com\/watch\?v=\w+((\&\w+=\w+)+)?)/g,'');}); 并测试了正则表达式(http://rubular.com/r/QiOvgv8stR),在那里它似乎可以工作,但在 jsFiddle 中却不行...所以我不知道原因。无论如何,如果必须的话,您可以手动从 URL 中删除额外的参数。 - Mottie
@fudgey 我修改了正则表达式,现在它可以正常工作了。请在jsFiddle上检查它,链接为http://jsfiddle.net/9r7pj/21/。 - Waseem Senjer
@Waseem:我刚刚注意到YouTube现在默认提供iframe代码。我猜这样它就可以在iPhone上运行了。只是提醒一下 ;) - Mottie

3

我和fudgey的思路基本相同,但是我对正则表达式更不擅长,所以我“借鉴”了他的代码直到那一点。我做出的一个改变是使用swfobject来嵌入视频而不是手工编写嵌入代码。这意味着你需要将swfobject库添加到页面中。

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

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>

对 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");                     
                })
            }
        })
    })

赞赏Fudgey的回答。

不错!我忘记了使用swfobject.js :) - Mottie

1
你需要使用类似以下的方式获取 div 的内容:

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

有了这个文本,您可以使用字符串操作或正则表达式来查找URL。 然后,您可以创建jQuery内容并添加:

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

并使用 jQuery 的操作方法将其添加到某个地方,例如

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

如果您需要更多详细信息,请提供更多细节。


我已经更新了我的问题,并附上了我的当前js。我添加了注释,说明我需要什么或我卡在哪里了。 - Amir

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接