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
I used URLSearchParams what Daniel A. White advised me in comment and it's work... :)
Code:
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: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.As for the reverse, if you wish to populate your form using JavaScript, you can get the values with this API as well: