Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

test string against multiple regexes in javascript

I want to test a given string against 20 or so regular expressions. What's a clean way to do this in Javascript? I'm more concerned about clean code and readability than efficiency (but I don't want it to be super slow either).

Right now I have:

if (href.indexOf('apple.com') > -1 ||
    href.indexOf('google.com') > -1 ||
    href.indexOf('yahoo.com') > -1 ||
    href.indexOf('facebook.com') > -1) {
    performDarkMagic()
}

But it's going to start looking kind of messy as that list grows. Maybe I could just create an array of regular expressions and execute something like _.any() and apply regex.test on each?

Edit: the strings/regexes to match may become more complicated, I just used simple URLs to make the example readable.

like image 714
mark Avatar asked Jun 06 '12 20:06

mark


1 Answers

Use the test function for regular expressions.

More information on regular expressions here. https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/RegExp

var re = /((google)|(facebook)|(yahoo)|(apple))\.com/;
re.test( str ); // returns true or false;

Test cases.

Live Demo Here: http://jsfiddle.net/rkzXP/1/

    var func = function( str ){
        var re = /((google)|(facebook)|(yahoo)|(apple))\.com/;
        return re.test( str );
    };
    test("test for valid values", function() {
        equal( func("google.com"), true);
        equal( func("facebook.com"), true);
        equal( func("apple.com"), true);
    });
    test("test for invalid values", function() {
        equal( func("googl.com"), false);
        equal( func("faceook.com"), false);
        equal( func("apple"), false);
    });

So you can rewrite your code as the following.

var re = /((google)|(facebook)|(yahoo)|(apple))\.com/;
if( re.test(str) ){
    performDarkMagic()
}
like image 145
Larry Battle Avatar answered Sep 28 '22 16:09

Larry Battle