How to convert a youtube video url to the iframe e

2020-05-19 09:41发布

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:

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

or

http://youtu.be/t-ZRX8984sc

2条回答
家丑人穷心不美
2楼-- · 2020-05-19 10:29

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.

查看更多
放我归山
3楼-- · 2020-05-19 10:40
var yturl= /(?:https?:\/\/)?(?:www\.)?(?:youtube\.com|youtu\.be)\/(?:watch\?v=)?([\w\-]{10,12})(?:&feature=related)?(?:[\w\-]{0})?/g;
var ytplayer= '<iframe width="640" height="360" src="http://www.youtube.com/embed/$1" frameborder="0" allowfullscreen></iframe>';
str.replace(yturl, ytplayer);

Ensure proper operation at the organization of WYSIWYG editor

查看更多
登录 后发表回答