Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
155
rated 0 times [  156] [ 1]  / answers: 1 / hits: 21392  / 10 Years ago, wed, october 8, 2014, 12:00:00

I am trying to create a function to remove a particular querystring and its value from the url .



For eg:
if i have a url like




var url = www.foo.com/test?name=kevin&gender=Male&id=1234




If i pass name -> it should remove the key and value for name. the url should become




www.foo.com/test?gender=Male&id=1234




i have a Function ReturnRefinedURL(key,url)



and i am doing this in the Function



function ReturnRefinedURL(key,url)
{
var Value = getParameterByName(key); // This returns kevin
var stringToBeRemoved = 'key +'='+ Value+'&'; // string becomes 'name=kevin&'
return url.replace(stringToBeRemoved, '');
}


//Found this in Google:



function getParameterByName(name) {
name = name.replace(/[[]/, \[).replace(/[]]/, \]);
var regex = new RegExp([\?&] + name + =([^&#]*)),
results = regex.exec(location.search);
return results == null ? : decodeURIComponent(results[1].replace(/+/g, ));
}


So when i call the method ReturnRefinedURL('name',window.location.href);



This works!!! But looking for a more elegant and fool proof method.

* This wont work if name parameter is the second one in the query string. (the '&' will still be retained)


More From » jquery

 Answers
25

Little bit of more search and then you can end up here:



 var url = www.foo.com/test?name=kevin&gender=Male&id=1234;
function removeURLParameter(url, parameter) {
//prefer to use l.search if you have a location/link object
var urlparts= url.split('?');
if (urlparts.length>=2) {

var prefix= encodeURIComponent(parameter)+'=';
var pars= urlparts[1].split(/[&;]/g);

//reverse iteration as may be destructive
for (var i= pars.length; i-- > 0;) {
//idiom for string.startsWith
if (pars[i].lastIndexOf(prefix, 0) !== -1) {
pars.splice(i, 1);
}
}

url= urlparts[0]+'?'+pars.join('&');
return url;
} else {
return url;
}
}

console.log(removeURLParameter(url, 'name'));
console.log(removeURLParameter(url, 'gender'));


Jsfiddle example


[#69193] Monday, October 6, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
micayla

Total Points: 148
Total Questions: 92
Total Answers: 109

Location: Aruba
Member since Sat, Oct 2, 2021
3 Years ago
micayla questions
Fri, Dec 24, 21, 00:00, 2 Years ago
Thu, Apr 16, 20, 00:00, 4 Years ago
Thu, Nov 14, 19, 00:00, 5 Years ago
;