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

标签 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);
}

最佳答案

不需要在这个上使用 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;
}

这里是 the Fiddle

更新:

代码现在处理 URL 上有散列的情况。

编辑

错过了一个案例!代码现在检查是否存在查询字符串

关于javascript - 使用 javascript 在 url 中添加/修改查询字符串/GET 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7640270/

相关文章:

c# - 我在 Chrome 中不断收到错误 : HTTP Error 403. 14 - 禁止使用 Web 应用程序 Visual Studio 2012

javascript - 如何在javascript中单击按钮时将图像放在另一个图像中

Javascript 通过文本框进行实时计算

java - Android:静态变量和移动复杂数据

vba - 迭代集合 (VBA)

javascript - 如果一个点在相机的视野之外,Three.js 线就会消失

c++ - 如何从另一个方法访问静态变量?

java - 如何在 IDEA 中创建结构替换以向类添加缺少的注释

r - 如何根据列组前缀替换列组的空白?

java - 与替代 Java 的组合