2

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 Answer 1

8

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.

Sign up to request clarification or add additional context in comments.

1 Comment

You may look for anything but a space since there could be some more text after the url this can be made doing this: ([^\ ]+) instead of (.+) here is an example: jsfiddle.net/w5grvL5q

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.