JohnMalcom
JohnMalcom

Reputation: 861

Replace random youtube link in text to embed code using javascript

I have some HTML code - for example:

<div>Text</div> 
http://www.youtube.com/watch?v=QZ2ekuCu4gM&feature=relmfu 
<div>Text</div> 
youtube.com/watch?v=adrJx864olE&feature=g-logo-xit
<div>Text</div>
<a href="#">LINK</a>

I need to automatically replace any YouTube URLs with iframes that embed the video at that URL, like the following:

<div>Text</div> 
<iframe width="560" height="315" 
src="http://www.youtube.com/embed/QZ2ekuCu4gM" frameborder="0" 
allowfullscreen></iframe>
<div>Text</div> 
<iframe width="560" height="315" 
src="http://www.youtube.com/embed/adrJx864olE" frameborder="0" 
allowfullscreen></iframe>
<div>Text</div>
<a href="#">LINK</a>

How can I search the HTML code for a link from YouTube and replace it with the equivalent iframe code using JavaScript?

Upvotes: 1

Views: 1378

Answers (1)

David Thomas
David Thomas

Reputation: 253318

Here's one way of doing it:

function linkYT(el) {
    if (!el) {
        return false;
    }
    else {
        var children = el.childNodes,
            text = [];
        for (var i=0, len=children.length; i<len; i++){
            var cur = children[i],
                nType = cur.nodeType,
                content = cur.nodeValue,
                url = 'http://www.youtube.com/embed/';
            if (nType == 3 && content.indexOf('youtube.com') > -1) {
                var embed = content.trim().match(/v=(\w+)/)[1],
                    iframe = document.createElement('iframe');
                iframe.src = url + embed;
                el.insertBefore(iframe, cur.nextSibling);
                cur.parentNode.removeChild(cur);
            }
        }
    }
}

var el = document.getElementById('content');
linkYT(el);​

JS Fiddle demo.

Please be aware there is no sanity-checking at all, and this approach requires that the video's identifier is prefaced with v= and terminated with a non-alphanumeric character.

I've tested and verified only in Opera 12, and Chromium 19.

To account for one other form of YouTube URL format:

function createIframe(embed, parent, after, url){
    if (!embed || !parent || !after) {
        return false;
    }
    else {
        url = url ? url : 'http://www.youtube.com/embed/';
        var iframe = document.createElement('iframe');
        iframe.src = url + embed;
        parent.insertBefore(iframe, after.nextSibling);
        parent.removeChild(after);
    }
}

function linkYT(el) {
    if (!el) {
        return false;
    }
    else {
        var children = el.childNodes,
            text = [];
        for (var i=0, len=children.length; i<len; i++){
            var cur = children[i],
                nType = cur.nodeType,
                content = cur.nodeValue,
                url = 'http://www.youtube.com/embed/';
            if (nType == 3) {
                if (content.indexOf('youtube.com') > -1) {
                    var embed = content.trim().match(/v=(\w+)/)[1];
                    createIframe(embed, el, cur);
                }
                else if (content.indexOf('youtu.be') > -1) {
                    var embed = content.trim().match(/be\/(\w+)/)[1];
                    createIframe(embed, el, cur);
                }
            }
        }
    }
}

var el = document.getElementById('content');
linkYT(el);​

JS Fiddle demo.

Effectively it's the same process, just with a slightly different Regular Expression.

Because there's two places in which the nodeType must be found equal to 3 and two places in which iframes are being created, I've wrapped the two indexOf() assessments inside of an if to test for the nodeType and abstracted iframe-creation to a separate function, both of which to simply avoid needless repetition.

References:

Upvotes: 5

Related Questions