views:

40

answers:

3

Can anyone tell me why, even when my alert shows that my regular expression strings match, the if statement is not triggered? I have sample code below. Thanks in advance.

$(document).ready(function () {
    $('div#primaryNavigation').find('a').each(function () {
        var pattern = /my-link1|my-link2|my-link3|my-link4/;
        var myWindow = window.location.pathname.match(pattern);
        var href = $(this).attr('href').match(pattern);
        alert('Show link and href until match: ' + myWindow + ' ' + href);
        if (myWindow == href) {
            //* Do Something *
        };
    });
});
A: 

Have you tried:

var pattern =/(my-link1|my-link2|my-link3|my-link4)/;
Diego
what about `/my-link[1-4]/`
jAndy
@jAndy I believe mylink1 etc are placeholders
Amarghosh
+4  A: 

The return value from .match() is not a string, it's an array of strings. Arrays don't compare as equal when they happen to contain the same values.

Try

if (myWindow[0] == href[0]) { ... }

Probably should also verify that the return values aren't null too:

if (myWindow && href && myWindow[0] === href[0]) { ... }
Pointy
That worked....Thanks for your help!
Brent
+2  A: 

Your if statement fails for the same reason [1,2,3] == [1,2,3] fails. You need to compare the contents of each list, or more simply compare myWindow[0] == href[0].

MikeWyatt