Javascript 获取两个值之间的youtube链接并替换为iframe

Javascript 获取两个值之间的youtube链接并替换为iframe,javascript,jquery,Javascript,Jquery,如果有如下html <div class="comment"> [youtube]http://www.youtube.com/watch?v=videoid1[/youtube] random text </div> <div class="comment"> [youtube]http://youtu.be/videoid2[/youtube] random text2 </div> 您可以使用RegExp(不是傻瓜)+jQuery.each

如果有如下html

<div class="comment">
[youtube]http://www.youtube.com/watch?v=videoid1[/youtube]
random text
</div>
<div class="comment">
[youtube]http://youtu.be/videoid2[/youtube]
random text2
</div>
您可以使用RegExp(不是傻瓜)+jQuery
.each()
.html()
方法来实现这一点

var youtubeTag = /\[youtube]https?:\/\/(?:www\.)?youtu(?:be\.com|\.be)\/(?:watch\?v=|v\/)?([A-Za-z0-9_-]+)([a-zA-Z&=;_+0-9*#-]*?)\[\/youtube]/,
    youtubeHTML = '<iframe width="420" height="315" src="http://www.youtube.com/embed/$1?rel=0" frameborder="0" allowfullscreen></iframe>';
$(".comment").each(function(){
    var $this = $(this);
    $this.html($this.html().replace(youtubeTag, youtubeHTML))
});
var youtubeTag=/\[youtube]https?:\/\/(?:www\)?youtu(?:be\.com\\.be)\/(?:watch\?v=| v\/)?([A-Za-z0-9\-]+)([A-Za-Z&=;\u0-9*\u35;-]*?)\[\/youtube]/,,
youtubeHTML='';
$(“.comment”).each(函数(){
var$this=$(this);
$this.html($this.html().replace(youtubeTag,youtubeHTML))
});
模式匹配:

  • [youtube]
  • 以http://或https://
  • (可选)后跟
    www.
  • 或者:
    youtube.com
    youtu.be
  • 后跟斜杠(
    /
  • 可选:
    watch?v=
    v/
  • YouTube视频ID(所有字母数字字符、下划线和连字符)
  • (可选)后跟查询字符串/位置哈希的另一部分
  • [/youtube]

@Ktash抱歉忘了提,但没关系Rob W的回答是这样的:。我正在使用.text()向您展示它是如何组合在一起的。但是当使用.html()时,它仍然不会呈现代码。但我不知道为什么。我们希望你自己尝试解决这个问题,而不是要求社区为你找到一个完整的解决方案。我有一个问题,如果链接末尾有&feature=grec_索引,这对例如[youtube]@Yusaf不起作用,如果我更新了我的答案。注意不要创建太放松的模式(即不是
*?
,尤其是不是
*
),因为这些模式也可能意外地匹配
[youtube]……观看?v=4568w不是URL blablabla[/youtube]
var youtubeTag = /\[youtube]https?:\/\/(?:www\.)?youtu(?:be\.com|\.be)\/(?:watch\?v=|v\/)?([A-Za-z0-9_-]+)([a-zA-Z&=;_+0-9*#-]*?)\[\/youtube]/,
    youtubeHTML = '<iframe width="420" height="315" src="http://www.youtube.com/embed/$1?rel=0" frameborder="0" allowfullscreen></iframe>';
$(".comment").each(function(){
    var $this = $(this);
    $this.html($this.html().replace(youtubeTag, youtubeHTML))
});