在JavaScript中从URL中删除查询参数

4

我正在尝试编写一个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;
}

有人发现这段代码存在问题或者想提出更好的实现方式吗?

谢谢!


我认为这可能是更好的地方 - http://codereview.stackexchange.com/ - Raj
2个回答

3

是的,看起来这个可以节省我大量的时间: http://medialize.github.com/URI.js/docs.html#search-remove - Chris Dutrow

2
给定一个百分比编码的URL,以下函数将从其查询字符串中删除字段-值对:
var removeQueryFields = function (url) {
    var fields = [].slice.call(arguments, 1).join('|'),
        parts = url.split( new RegExp('[&?](' + fields + ')=[^&]*') ),
        length = parts.length - 1;
    return parts[0] + '?' + (length ? parts[length].slice(1) : '');
}

一些例子:
var string = 'http://server/path/program?f1=v1&f2=v2';
removeQueryFields( string, 'f1' );       // 'http://server/path/program?f2=v2'
removeQueryFields( string, 'f2' );       // 'http://server/path/program?f1=v1'
removeQueryFields( string, 'f1', 'f2' ); // 'http://server/path/program'

1
当最后一个参数被移除时,这将删除URL上的任何片段。 - Mike Samuel
因为他的RegExp表达式有误,当参数值为空时,它将无法正常工作。我使用了这个脚本并在意识到它无法正常工作时进行了修复:new RegExp('[&?](' + fields + ')=.[^&].') ) - aleation

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接