user7158745 user7158745 - 25 days ago 11
Javascript Question

Check if URL matches multiple regex variables?

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.

Answer

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