我正在尝试编写一个JavaScript函数,它可以从URL中删除查询参数。我使用了正则表达式,但不确定是否有遗漏。而且,我觉得可能有更好的方法来完成这个任务,而不必花费大量时间在正则表达式上,还要担心是否遗漏了一些特殊情况。
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;
}
有人发现这段代码存在问题或者想提出更好的实现方式吗?
谢谢!