Question

I'm sure this is very easy and I've seen similar questions, but none have helped me figure out why this wont work. Couldn't anyone tell me why this doesn't catch when currentPage is set as faq or contact?

<script type="text/javascript">
                function init() {
                document.getElementById('searchSubmit').onclick=function(){
                        var uriArgs = window.location.search;
                        var currentPage = uriArgs.match(/page=?(\w*)/);
                        if ( (currentPage == null) || (currentPage == 'faq') || (currentPage == 'contact') ) {
                                currentPage = "index";
                                document.getElementById('searchHidden').value = currentPage;
                        }
                        else {
                                document.getElementById('searchHidden').value = currentPage[1];
                        }
                }
                }
                window.onload=init;
        </script>

I set an alert to popup so I could see whether or not it was properly being set as faq or contact and it was so I'm not sure why the if statement isn't catching that.

Thanks in advanced!

Was it helpful?

Solution

If there is a match, String.match will return the capture group at index 1 of the array. Example:

> 'page=sdfsfsdf'.match(/page=?(\w*)/)
["page=sdfsfsdf", "sdfsfsdf"]

So you need to look inside of the array returned by match (assuming it is not null).

if (currentPage == null || currentPage[1] == 'faq' || currentPage[1] == 'contact') {
    /* ... */       
}

OTHER TIPS

Your problem is not with the if-statement, but with the result of the match method: It returns an array of the match and the matched groups - you want to compare to the first matched group.

var match = window.location.search = uriArgs.match(/page=?(\w*)/),
    currentPage = false;
if (match != null)
    currentPage = match[1];

if ( !currentPage || currentPage=='faq' || currentPage=='contact' ) {
    // do something
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top