使用javascript在URL中添加/修改查询字符串/ GET变量

MLM*_*MLM 5 javascript variables replace get query-string

所以我想在url中替换GET变量值,如果变量不存在,则将其添加到url.

编辑:我这样做的元素href不是页面的当前位置..

我不擅长使用javascript,但我确实知道如何使用jQuery以及javascript的基础知识.我知道如何编写正则表达式但不知道如何使用正则表达式的javascript语法以及使用它的函数.

这是我到目前为止,它在第3行有一个错误:在jsfiddle(或下面)看到它:http://jsfiddle.net/MadLittleMods/C93mD/

function addParameter(url, param, value) {
    var pattern = new RegExp(param + '=(.*?);', 'gi');
    return url.replace(pattern, param + '=' + value + ';');

    alert(url);
}
Run Code Online (Sandbox Code Playgroud)

Rya*_*nal 15

不需要在这个上使用jQuery.正则表达式和字符串函数就足够了.请参阅下面的评论代码:

function addParameter(url, param, value) {
    // Using a positive lookahead (?=\=) to find the
    // given parameter, preceded by a ? or &, and followed
    // by a = with a value after than (using a non-greedy selector)
    // and then followed by a & or the end of the string
    var val = new RegExp('(\\?|\\&)' + param + '=.*?(?=(&|$))'),
        parts = url.toString().split('#'),
        url = parts[0],
        hash = parts[1]
        qstring = /\?.+$/,
        newURL = url;

    // Check if the parameter exists
    if (val.test(url))
    {
        // if it does, replace it, using the captured group
        // to determine & or ? at the beginning
        newURL = url.replace(val, '$1' + param + '=' + value);
    }
    else if (qstring.test(url))
    {
        // otherwise, if there is a query string at all
        // add the param to the end of it
        newURL = url + '&' + param + '=' + value;
    }
    else
    {
        // if there's no query string, add one
        newURL = url + '?' + param + '=' + value;
    }

    if (hash)
    {
        newURL += '#' + hash;
    }

    return newURL;
}
Run Code Online (Sandbox Code Playgroud)

这是小提琴

更新:

代码现在处理URL上有哈希的情况.

编辑

错过了一个案子!现在,该代码检查,看看是否有查询字符串在所有.