使用 JavaScript 更改 URL 参数并指定默认值

新手上路,请多包涵

我有这个网址:

site.fwx?position=1&archiveid=5000&columns=5&rows=20&sorting=ModifiedTimeAsc

我需要的是能够将’rows’ url参数值更改为我指定的值,比如说10。如果’rows’不存在,我需要将它添加到url的末尾并添加我已经指定的值 (10)。

原文由 Sindre Sorhus 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 798
2 个回答

4年后,在学到了很多东西之后回答我自己的问题。特别是你不应该对所有事情都使用 jQuery。我创建了一个可以解析/字符串化查询字符串的简单模块。这使得修改查询字符串变得容易。

您可以按如下方式使用 查询字符串

 // parse the query string into an object
 var q = queryString.parse(location.search);
 // set the `row` property
 q.rows = 10;
 // convert the object to a query string
 // and overwrite the existing query string
 location.search = queryString.stringify(q);

原文由 Sindre Sorhus 发布,翻译遵循 CC BY-SA 3.0 许可协议

我已经扩展了 Sujoy 的代码来组成一个函数。

 /**
 * http://stackoverflow.com/a/10997390/11236
 */
function updateURLParameter(url, param, paramVal){
    var newAdditionalURL = "";
    var tempArray = url.split("?");
    var baseURL = tempArray[0];
    var additionalURL = tempArray[1];
    var temp = "";
    if (additionalURL) {
        tempArray = additionalURL.split("&");
        for (var i=0; i<tempArray.length; i++){
            if(tempArray[i].split('=')[0] != param){
                newAdditionalURL += temp + tempArray[i];
                temp = "&";
            }
        }
    }

    var rows_txt = temp + "" + param + "=" + paramVal;
    return baseURL + "?" + newAdditionalURL + rows_txt;
}

函数调用:

 var newURL = updateURLParameter(window.location.href, 'locId', 'newLoc');
newURL = updateURLParameter(newURL, 'resId', 'newResId');

window.history.replaceState('', '', updateURLParameter(window.location.href, "param", "value"));

更新版本也处理 URL 上的锚点。

 function updateURLParameter(url, param, paramVal)
{
    var TheAnchor = null;
    var newAdditionalURL = "";
    var tempArray = url.split("?");
    var baseURL = tempArray[0];
    var additionalURL = tempArray[1];
    var temp = "";

    if (additionalURL)
    {
        var tmpAnchor = additionalURL.split("#");
        var TheParams = tmpAnchor[0];
            TheAnchor = tmpAnchor[1];
        if(TheAnchor)
            additionalURL = TheParams;

        tempArray = additionalURL.split("&");

        for (var i=0; i<tempArray.length; i++)
        {
            if(tempArray[i].split('=')[0] != param)
            {
                newAdditionalURL += temp + tempArray[i];
                temp = "&";
            }
        }
    }
    else
    {
        var tmpAnchor = baseURL.split("#");
        var TheParams = tmpAnchor[0];
            TheAnchor  = tmpAnchor[1];

        if(TheParams)
            baseURL = TheParams;
    }

    if(TheAnchor)
        paramVal += "#" + TheAnchor;

    var rows_txt = temp + "" + param + "=" + paramVal;
    return baseURL + "?" + newAdditionalURL + rows_txt;
}

原文由 Adil Malik 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题