如何在页面加载时使用jQuery将youtube视频网址转换为iframe嵌入代码? [英] How to convert a youtube video url to the iframe embed code, using jQuery on page load?

查看:128
本文介绍了如何在页面加载时使用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.

这篇关于如何在页面加载时使用jQuery将youtube视频网址转换为iframe嵌入代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆