Question

I have a scenario to get Query Params from the URL. There is a method called toQueryParams() which will get all params. But when the URL is http://www.google.com the same method returning the same URL as query param, URL as key and undefined as value.

var param = window.location.href.toQueryParams()

This is the code I have used.

Was it helpful?

Solution

When the URL has no query parameters ie no ? or & part of the URL then there are no query parameters except for the URL.

So how I usually use this method on a given URL http://www.mywebsite.com/index.php?arg=2500&search=Smith

var param = window.location.href.toQueryParams();
if(param.arg != undefined)
{
    //do things with the arg parameter
}
if(param.search != undefined)
{
    //do things with the search param
    alert('User has selected '+param.search+' as the search parameter');
}

So if the given param does not exist then I don't try and handle it. The method toQueryParam() is giving you a error you can handle instead of an Exception or full on JS error that stops your JS execution.

OTHER TIPS

I tried in the following way, to resolve this issue.

if (window.location.search != "") { // this means the url has no query params
var param = window.location.href.toQueryParams(); // param Object will holds queryparams in key and value form
} else {
var param = new Object(); // param will has no queryParmas but, it is an empty object
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top