How can I replace youtube / vimeo url with embed code in javascript code?

醉酒当歌 提交于 2020-01-22 16:28:09

问题


I've tried replace youtube and vimeo url with embed code in javascript code.

I've used this code:

EXAMPLE 1:

HTML:

<div id="divContent"></div>

JAVASCRIPT:

$("#divContent").html('http://www.youtube.com/watch?v=t-ZRX8984sc <br /> http://vimeo.com/82495711 <br /> http://youtu.be/t-ZRX8984sc');

$('#divContent').html(function(i, html) {
    return html.replace(/(?:http:\/\/)?(?:www\.)?(?:youtube\.com|youtu\.be)\/(?:watch\?v=)?(.+)/g, '<iframe width="200" height="100" src="http://www.youtube.com/embed/$1" frameborder="0" allowfullscreen></iframe>').replace(/(?:http:\/\/)?(?:www\.)?(?:vimeo\.com)\/(.+)/g, '<iframe src="//player.vimeo.com/video/$1" width="200" height="100" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>');

});

DEMO EXAMPLE 1: http://jsfiddle.net/88Ms2/301/ - It's not working.

EXAMPLE 2

HTML:

<div id="divContent">
http://www.youtube.com/watch?v=t-ZRX8984sc
    <br />
http://vimeo.com/82495711
    <br />
http://youtu.be/t-ZRX8984sc
</div>

JAVASCRIPT:

$('#divContent').html(function(i, html) {
    return html.replace(/(?:http:\/\/)?(?:www\.)?(?:youtube\.com|youtu\.be)\/(?:watch\?v=)?(.+)/g, '<iframe width="200" height="100" src="http://www.youtube.com/embed/$1" frameborder="0" allowfullscreen></iframe>').replace(/(?:http:\/\/)?(?:www\.)?(?:vimeo\.com)\/(.+)/g, '<iframe src="//player.vimeo.com/video/$1" width="200" height="100" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>');

});

DEMO EXAMPLE 2: http://jsfiddle.net/88Ms2/300/ - It's working

I've retrieved a data from database using ajax. I need the data with html code insert into div using javascript. How can I modify the example 1 to the correct code?


回答1:


In example 1, change the javascript code to:

$('#divContent').contents()
    .filter(function(){
        return this.nodeType === 3;
     })
    .map(function(index, text){
        $(text).replaceWith(
            text.textContent.replace(/(?:http:\/\/)?(?:www\.)?(?:youtube\.com|youtu\.be)\/(?:watch\?v=)?(.+)/g, '<iframe width="200" height="100" src="http://www.youtube.com/embed/$1" frameborder="0" allowfullscreen></iframe>').replace(/(?:http:\/\/)?(?:www\.)?(?:vimeo\.com)\/(.+)/g, '<iframe src="//player.vimeo.com/video/$1" width="200" height="100" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>')
        );    
    })

It should work now.



来源:https://stackoverflow.com/questions/20915664/how-can-i-replace-youtube-vimeo-url-with-embed-code-in-javascript-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!