Javascript 获取两个值之间的youtube链接并替换为iframe
如果有如下htmlJavascript 获取两个值之间的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
<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]
*?
,尤其是不是*
),因为这些模式也可能意外地匹配[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))
});