简体   繁体   中英

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("?") > 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

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(/[\\?\\&]/)) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM