如何在页面加载时使用jQuery将youtube视频网址转换为iframe嵌入代码?

问题描述:

我有一个WYSIWYG textarea,有时用户可能会在框中输入youtube网址。在服务器端,有html过滤器,以防止有害代码被保存。

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.

所以相反,我想保持服务器代码原样,并运行一个jQuery文档就绪事件,搜索youtube链接的文本块,并将其转换为iframe嵌入代码。

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).

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

http://youtu.be/t-ZRX8984sc


此正则表达式将获取URL并根据YouTube目前输出的内容替换 embed 标记(只需 iframe )。

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.