I’m trying to do a URL GET variable replace, however the regular expression for checking whether the variable exists in amongst other GET variables is returning true when I am expecting it to return false.
The pattern I am using is: &sort=.*&
Test URL: http://localhost/search?location=any&sort=asc
Am I right to believe that this pattern should be returning false on the basis that their is no ampersand character following the sort parameter’s value?
Full code:
var sort = getOptionValue($(this).attr('id'));
var url = document.URL;
if(url.indexOf('?') == -1) {
url = url+'?sort='+sort;
} else {
if(url.search('/&sort=.*&/i')) {
url.replace('/&sort=.*&/i','&sort='+sort+'&');
}
else if(url.search('/&sort=.*/i')) {
url.replace('/&sort=.*/i','&sort='+sort);
}
}
Well, you are using String.search, which, according to the linked documentation:
So it will return
-1, or0or greater when there is a match. So you should test for-1, not truthiness.Also, there is no need to pass the regexes as strings, you might as well use:
Further, keep in mind that
replacewill create a new string, not replace in the string (strings in Javascript are immutable).Finally, I don’t see the need for searching for the string, and then replacing it — it seems that you always want to replace
&sort=SOMETHINGwith&sort=SOMETHING_ELSE, so just do that: