Reputation: 24019
I have the following which checks URL variables:
$.urlParam = function(name) {
var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
return results[1] || 0;
};
I want to set variables only if they are present in the URL.
Example URL:
http://myUrl.com/search?searchTerm=red
Example JS, which works correctly:
if(typeof $.urlParam('searchTerm') != 'undefined'){
var searchTerm = $.urlParam('searchTerm');
}
However, if I try the following (checking for another variable) the code fails, yet with no error in the FF console:
if(typeof $.urlParam('storeSearch') != 'undefined'){
var storeSearch = $.urlParam('storeSearch');
}
Is there a better way to check if a URL variable is set and then assign that value to a javascript variable?
Upvotes: 0
Views: 75
Reputation: 437904
Your function can never return undefined
, so the check you are using will never work correctly.
An immediate improvement would be to change the function to return undefined
appropriately:
$.urlParam = function(name) {
var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
return results[1]; // undefined if no match for capturing group 1
};
However, this will still not be good enough because if your regex does not match at all then exec
returns null
and null[1]
will produce an error. So improve it further to:
$.urlParam = function(name) {
var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
return (results || undefined) && results[1];
};
results || undefined
evaluates to either an array (which may or may not have an [1]
element). If it resolves to undefined
, then undefined && results[1]
is also undefined
. If it resolves to an array, then either [1]
evaluates to the second element if one exists, or to undefined
if it does not.
In all cases the final value is either undefined
or the matched contents of the capturing group.
Upvotes: 1