How to replace previous URL parameters using javascript?

问题: I had this function to get and replace my URL parameter: function getURLParameters(paramName) { var sURL = window.document.URL.toString(); if (sURL.indexOf("?") &...

问题:

I had this function to get and replace my URL parameter:

function getURLParameters(paramName) {
    var sURL = window.document.URL.toString();
    if (sURL.indexOf("?") > 0) {
        var arrParams = sURL.split("?");
        var arrURLParams = arrParams[1].split("&");
        var arrParamNames = new Array(arrURLParams.length);
        var arrParamValues = new Array(arrURLParams.length);

        var i = 0;
        for (i = 0; i < arrURLParams.length; i++) {
            var sParam = arrURLParams[i].split("=");
            arrParamNames[i] = sParam[0];
            if (sParam[1] !== "")
                arrParamValues[i] = unescape(sParam[1]);
            else
                arrParamValues[i] = "No Value";
        }

        for (i = 0; i < arrURLParams.length; i++) {
            if (arrParamNames[i] === paramName) {
                return arrParamValues[i];
            }
        }
        return "No Parameters Found";
    }

}

It was working okay when I had a URL like this

https://example.com/?&page=2

But now, my URL is like this:

https://example.com/?&page=2&order=my_id&direction=ASC.

My function still replaces page=2 as page=3 etc, but other values are appended to my whole URL. How can I replace all these params in my URL


回答1:

You can use split by both ? and & to get all of the params then you process them by your logic after that.

const url = "https://example.com/?&page=2&order=my_id&direction=ASC"
console.log(url.split(/[?&]/))

  • 发表于 2019-02-22 05:27
  • 阅读 ( 169 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除