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

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.


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