skip to Main Content

I have inputs type="text", selects and other elements used for filters. After change any of these i need to refresh page with all url parameters. I need to read all URL parameters, process them and build new URL string for redirect.

In PHP it’s easy, something like this:

$domain = 'index.php?';
foreach($_GET as $key => $value){
    $domain .= $key.'='.$value.'&'; // there I can do changes what I need
}
$domain = substr($domain, 0, strlen($domain)-5); // $domain contents full URL with changed parameters

How to do the same in JavaScript?

2

Answers


  1. Chosen as BEST ANSWER

    I used URLSearchParams what Daniel A. White advised me in comment and it's work... :)

    Code:

    let domain = 'index.php?';
    let url = new URL(window.location.href);
    let params = new URLSearchParams(url.search.slice(1));
    
    params.set('key', 'value'); // there I can change parameter what I need
    
    domain += params.toString(); // domain contents full URL with changed parameters
    

  2. There’s the very useful URL api for this. It has a property that contains the query string key/values.

    Let’s say you want to add the value name with value "alice" to the current URL. If a name is already set, the new value should overwrite the old:

    const url = new URL(window.location.href);
    // In the query parameters ("?foo=bar") part of the URL, set a new value.
    url.searchParams.set("name", "alice");
    // Redirect to the new URL.
    window.location = url.toString();
    

    This will take care of adding either a question mark or an ampersand—no need to check that yourself.

    Since you’re working with PHP, you might encounter a need to not overwrite an existing value, since PHP considers ?tags[]=apple&tags[]=banana an array.

    url.searchParams.append("tags[]", "apple");
    url.searchParams.append("tags[]", "banana");
    

    As for the reverse, if you wish to populate your form using JavaScript, you can get the values with this API as well:

    const url = new URL(window.location.href);
    // For singular values:
    someTextField.value = url.searchParams.get("name");
    // For multiple values:
    for (const value of url.searchParams.getAll("tags[]")) {
      // do something with `value`.
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search