Chaddeus Chaddeus - 1 year ago 127
Javascript Question

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:


Answer Source

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="$1" frameborder="0" allowfullscreen></iframe>');


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 =\/\/)?(?:www\.)?(?:youtube\.com|youtu\.be)\/(?:watch\?v=)?(.+)/g);

    if (!matches) {
        return true;

    var iframe = $('<iframe width="420" height="345" frameborder="0" allowfullscreen />', {
        src: '' + matches[1]




Note that this inserts after the entire text node.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download