3

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

  • Possible duplicate of [How to get the value from the GET parameters?](https://stackoverflow.com/questions/979975/how-to-get-the-value-from-the-get-parameters) and [How can I get query string values in JavaScript?](https://stackoverflow.com/questions/901115) – adiga Feb 21 '19 at 05:03
  • Check the duplicates. Use [**URL**](https://developer.mozilla.org/en-US/docs/Web/API/URL) and [**URLSearchParams**](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams) instead of manually splitting and looping. Like this: `new URL( window.document.URL).searchParams.get(paramName)` – adiga Feb 21 '19 at 05:05

1 Answers1

0

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(/[\?\&]/))
holydragon
  • 6,158
  • 6
  • 39
  • 62