I use this function to parse url parameters
function parseURL(url) {
var a = document.createElement('a');
a.href = url;
return {
source: url,
protocol: a.protocol.replace(':',''),
host: a.hostname,
port: a.port,
query: a.search,
params: (function(){
var ret = {},
seg = a.search.replace(/^\?/,'').split('&'),
len = seg.length, i = 0, s;
for (;i<len;i++) {
if (!seg[i]) { continue; }
s = seg[i].split('=');
ret[s[0]] = s[1];
}
return ret;
})(),
file: (a.pathname.match(/\/([^\/?#]+)$/i) || [,''])[1],
hash: a.hash.replace('#',''),
path: a.pathname.replace(/^([^\/])/,'/$1'),
relative: (a.href.match(/tps?:\/\/[^\/]+(.+)/) || [,''])[1],
segments: a.pathname.replace(/^\//,'').split('/')
};
}
I can call this function by:
var currentURL = parseURL(window.location.href);
console.log(currentURL.params['price']);
But I'm trying to figure out the length of params..to verify if has any parameter already.
console.log(currentURL.params.length) // doesn't work -> returns undefined
Now you ask me: why do you want to know the length? Because I have another function:
function filter(type, currentURL){
var result = "";
var url = document.location.href;
if(currentURL.params[type] != undefined){
var price = currentURL.params[type];
if(url.indexOf('&' + type + '=asc') > 0){
result = url.replace("&" + type + "=asc", "&" + type + "=desc");
}else if(url.indexOf("?" + type + "=asc") > 0){
result = url.replace("?" + type + "=asc", "?" + type + "=desc");
}else if(url.indexOf("&" + type + "=desc") > 0){
result = url.replace("&" + type + "=desc", "&" + type + "=asc");
}else if(url.indexOf("?" + type + "=desc") > 0){
result = url.replace("?" + type + "=desc", "?" + type + "=asc");
}
}else{
result = url + "&" + type + "=asc";
if(currentURL.length == 0){
// The problem is here
result = url + "?" + type + "=asc";
}
}
return result;
}
Because if I have no parameters, I should put: index.php?price=asc and NOT index.php&price=asc.
Edit: Solved with @Pointy help.
result = url + "&" + type + "=asc";
if(window.location.search.length == 0){
result = url + "?" + type + "=asc";
}
some/url?length=42?window.locationobject already separates out the different parts of the URL.window.location.searchis everything after the?for example. Documentation?price=asc, otherwise, if I have already parameters in the URL, I should redirect to:parameters&price=asc