1

I am making a jquery plugin which will embed videos from youtube and vimeo (and eventually other sites). Right now I have this code:

(function($) { 
    $.fn.embedFrame = function() {
        var youtube = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=)([^#\&\?]*).*/;
        var vimeo = /(?:http?s?:\/\/)?(?:www\.)?(?:vimeo\.com)\/?(.+)/g;

        this.filter("a").html(function() {
            // CHECK IF THE LINK HREF MATCHES ANY OF THE ABOVE REGEX VARIABLE RULES

            // IF THE HREF MATCHES, RETURN AN IFRAME EMBED OF THE VIDEO
        });

        return this;
    };
}(jQuery));

I have a few questions:

  1. How can I check if the link href matches any of the regex rules?
  2. Is there a better way to organize my code? I plan to add many more video sites in the future.

Thanks.

1 Answer 1

1

Keep your regular expressions in an array or object, and then just iterate and check if the links match any of them

(function($) { 
    $.fn.embedFrame = function() {
        var filter = {
            youtube : /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=)([^#\&\?]*).*/,
            vimeo   : /(?:http?s?:\/\/)?(?:www\.)?(?:vimeo\.com)\/?(.+)/g
        }

        var videos = this.filter(function(_, el) {
            if ( el.tagName.toLowerCase() !== 'a' ) return false;

            return Object.keys(filter).some(function(reg) {
                return filter[reg].test( el.href );
            });
        });

        return this;
    };
}(jQuery));

FIDDLE

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

1 Comment

That works great, thanks! How would I register an "on click" event within the plugin so that I can embed a link when it's clicked on?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.