从javascript中的URL中删除查询参数

时间:2012-01-01 08:07:24

标签: javascript regex url uri

我正在尝试编写一个函数,它将从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;
}

是否有人发现此代码存在任何问题,或者想建议更好的实施方式或解决方法?

谢谢!

2 个答案:

答案 0 :(得分:3)

如果您有很多与URL相关的操作,那么最好试试这个非常棒的js库https://github.com/medialize/URI.js

答案 1 :(得分:2)

给定percent-encoded 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'