convert youtube links to jwplayer embed code
I have a chat and when a person sends a youtube link I would like to instantly convert it to playable video.
So when a user sends a link in the following formats
http://www.youtube.com/watch?v=kLORyXO8mVc
http://www.youtube.com/watch?v=kLORyXO8mVc&feature=related
It will convert the link to this code
<div id='mediaspace'>Youtube</div>
<script type='text/javascript'>
jwplayer('mediaspace').setup({
'flashplayer': 'player.swf',
'file': 'XXXXXX-YOUTUBE-VIDEO-URL-GOES-HERE-XXXXXX',
'controlbar': 'bottom',
'width': '350',
'height': '230'
});
</script>
Also is it possible to only take the youtube link in this format
http://www.youtube.com/watch?v=kLORyXO8mVc
and any links that a users sends having &feature
or more attached to it will be remove only having the standard url like this http://www.youtube.com/watch?v=kLORyXO8mVc
here is what i came up with but its not working:
$().ready(function() {
var regEx = /http://(www\.)?youtube\.com/watch\?.*v=([a-zA-Z0-9]+)/;
$("body").filter(function() {
return $(this).html().match(regEx);
}).each(function() {
$(this).html($(this).html().replace(regEx, '
<div id='mediaspace'>Youtube</div>
<script type='text/javascript'>
jwplayer('mediaspace').setup({
'flashplayer': 'player.swf',
'file': '$1',
'con开发者_运维技巧trolbar': 'bottom',
'width': '350',
'height': '230'
});
</script>
'));
});
});
Your code had no escaping in the regular expression (you can't use / inside / without escaping), or your replacement string (you can't use ' inside ' without escaping). Try this:
var regEx = /http:\/\/(www\.)?youtube\.com\/watch\?.*v=([a-zA-Z0-9]+)/;
$("body").filter(function() {
return $(this).html().match(regEx);
}).each(function() {
$(this).html($(this).html().replace(regEx, "<div id='mediaspace'>Youtube</div><script type='text/javascript'>jwplayer('mediaspace').setup({'flashplayer': 'player.swf','file': '$1','controlbar': 'bottom','width': '350','height': '230'});</scr"+"ipt>"));
});
精彩评论