I defined a query string catid as:
mydomain.com/?catid=
How to remove ?catid in my url if it's empty please?
I defined a query string catid as:
mydomain.com/?catid=
How to remove ?catid in my url if it's empty please?
The code from the very similar question from Jerome Brunel isn't working with your particular request.
var arr=['mydomain.com/?catid=','mydomain.com/?catid=1&id1=','mydomain.com/?catid=&id=1','mydomain.com/?catid=&id=','mydomain.com/?catid=&id=&id2=','mydomain.com/?catid=&id=1&id2=&id3=1&id4=&id5=1&id6=2'];
function removeEmptyQueryParameters(s) {
return s.replace(/([\?&])([^=]+=($|&))+/g,'$1').replace(/[\?&]$/g,'');
}
arr.forEach(function(s) {
console.log(s,removeEmptyQueryParameters(s));
});
I think it's will be the most semantically-correct way:
url = 'mydomain.com/?catid='
url = url.split('?')
if (url.length > 1) {
params = url[1].split('&');
params = params.map(function(e){ return e.split('='); });
params = params.filter(function(e){ return (e.length > 1) && (e[1].length > 0); });
url = url[0];
if (params.length > 0) {
url += '?' + params.map(function(e){ return e.join('='); }).join('&');
}
} else {
url = url[0];
}