i saw some similar post at Stack, but i want to ask for specific function in jquery that is
$.urlParam('GETparameter')
Why simple
if($.urlParam('GETparameter') === undefined)
not working? And why there are complex answers at other questions?
Thank you for answers
This is an overdue update, but as Frits's solution notes, using URLSearchParams
is now the best approach.
const getQueryParameter = (param) => new URLSearchParams(document.location.search.substring(1)).get(param);
First off, $.urlParam
is not an inherent jQuery function as far as I can tell, meaning you'll need to define it if you plan on using it.
When looking it up, I found a user-created function of the same name; I am going to assume that this is what you're referring to:
$.urlParam = function(name){
var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
return results[1] || 0;
}
It looks like this will return 0
if the parameter is not found, rather than undefined
. If this function is in fact the one you're referencing, you'll want to do this instead:
if($.urlParam('GETparameter') === 0)
Another solution here is the URLSearchParams
function.
As an example, if your URL was https://example.com?foo=bar&baz=qux
you could retrieve all of the parameters and then query the specific one like this:
var urlParams = new URLSearchParams(window.location.search); //get all parameters
var foo = urlParams.get('foo'); //extract the foo parameter - this will return NULL if foo isn't a parameter
if(foo) { //check if foo parameter is set to anything
alert('FOO EXISTS');
}
if(foo == 'bar') { //check if foo parameter is 'bar'
alert('FOO == BAR');
}
If you want to check type of variable, you need to use something like:
if (typeof($.urlParam('GETparameter')) === 'undefined') {
..
}
typeof documentation
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With