1

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?

1
  • I read the html text from the database and I want to do the following rewrite using javascript on client side. Commented Jul 23, 2012 at 22:26

1 Answer 1

5

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:

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

6 Comments

David i have a problem. I read the data using ajax into a div and now isn't work. :( I have an empty div: <div id="Content"></div> How can i modify your solution?
Did you call the function again, after the Ajax content had loaded? The function will only run once, not continually and, if new content is added, the function must be called to parse that content.
Url is inside the html code - it is a problem. How do I fix this? Help me please David. :-)
I'd love to; I'm stuck in your demo though, since there's only one element being appended to the page, with no text. What's meant to be happening?
As far as I can see, this should work, and does in my (perhaps limited) demo.
|

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.