I am trying to write a function that will remove a request argument from a url in javascript. I think I use regex, but I'm not sure if I missed something. In addition, I cannot shake the feeling that there was probably the best way to do this, which did not include me all the time with regular expression, and risking later to find out that I did not take any angle case.
remove_query_argument = function(url, arg){ var query_arg_regex; // Remove occurences that come after '&' symbols and not the first one after the '?' query_arg_regex = new RegExp('&' + arg + '=[^(?:&|$)]*', 'ig'); url = url.replace(query_arg_regex, ''); // remove the instance that the argument to remove is the first one query_arg_regex = new RegExp('[?]' + arg + '[^(?:&|$)]*(&?)', 'i'); url = url.replace(query_arg_regex, function (match, capture) { if( capture != '&' ){ return ''; }else{ return '?' } }); return url; }
Does anyone see any problems with this code or would like to suggest a better implementation or a way to do this?
Thanks!
source share