Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a youtube video url to the iframe embed code, using jQuery on page load?

I have a WYSIWYG textarea, and sometimes user's may enter a youtube url into the box. On the server side, there are html filters to prevent "harmful" code from being saved.

So instead, I'd like to just keep the server code as-is, and run a jQuery document ready event that searches a block of text for a youtube link, and converts it to the iframe embed code.

I'd imagine it would be regex based, but I'm absolutely horrid with regex's (at some point, I really need to sit down and study them).

Two types of youtube links:

http://www.youtube.com/watch?v=t-ZRX8984sc

or

http://youtu.be/t-ZRX8984sc
like image 628
Chaddeus Avatar asked Aug 24 '11 00:08

Chaddeus


Video Answer


2 Answers

This regex will pick up the URLs and replace them with the embed markup (just an iframe according to what YouTube currently outputs).

str.replace(/(?:http:\/\/)?(?:www\.)?(?:youtube\.com|youtu\.be)\/(?:watch\?v=)?(.+)/g, '<iframe width="420" height="345" src="http://www.youtube.com/embed/$1" frameborder="0" allowfullscreen></iframe>');

jsFiddle.

However, this can mangle things such as event handlers attached with old school methods.

It is a bit more complicated, but the best way would be work with text nodes only.

That should look something like this...

$('body').contents().each(function() {

    // Skip non text nodes.
    if (this.nodeType !== 3) {
        return true;
    }

    // Grab text
    var matches = this.data.match(/(?:http:\/\/)?(?:www\.)?(?:youtube\.com|youtu\.be)\/(?:watch\?v=)?(.+)/g);

    if (!matches) {
        return true;
    }

    var iframe = $('<iframe width="420" height="345" frameborder="0" allowfullscreen />', {
        src: 'http://www.youtube.com/embed/' + matches[1]
    });

    iframe.insertAfter(this);

    $(this).remove();

});

Note that this inserts after the entire text node.

like image 105
alex Avatar answered Oct 08 '22 21:10

alex


var yturl= /(?:https?:\/\/)?(?:www\.)?(?:youtube\.com|youtu\.be)\/(?:watch\?v=)?([\w\-]{10,12})(?:&feature=related)?(?:[\w\-]{0})?/g;
var ytplayer= '<iframe width="640" height="360" src="http://www.youtube.com/embed/$1" frameborder="0" allowfullscreen></iframe>';
str.replace(yturl, ytplayer);

Ensure proper operation at the organization of WYSIWYG editor

like image 33
X-NicON Avatar answered Oct 08 '22 20:10

X-NicON