Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a parameter to the URL with JavaScript

In a web application that makes use of AJAX calls, I need to submit a request but add a parameter to the end of the URL, for example:

Original URL:

http://server/myapp.php?id=10

Resulting URL:

http://server/myapp.php?id=10&enabled=true

Looking for a JavaScript function which parses the URL looking at each parameter, then adds the new parameter or updates the value if one already exists.

like image 896
Lessan Vaezi Avatar asked Jan 28 '09 08:01

Lessan Vaezi


2 Answers

You can use one of these:

  • https://developer.mozilla.org/en-US/docs/Web/API/URL
  • https://developer.mozilla.org/en/docs/Web/API/URLSearchParams

Example:

var url = new URL("http://foo.bar/?x=1&y=2");  // If your expected result is "http://foo.bar/?x=1&y=2&x=42" url.searchParams.append('x', 42);  // If your expected result is "http://foo.bar/?x=42&y=2" url.searchParams.set('x', 42); 
like image 171
Vianney Bajart Avatar answered Oct 10 '22 21:10

Vianney Bajart


A basic implementation which you'll need to adapt would look something like this:

function insertParam(key, value) {     key = encodeURIComponent(key);     value = encodeURIComponent(value);      // kvp looks like ['key1=value1', 'key2=value2', ...]     var kvp = document.location.search.substr(1).split('&');     let i=0;      for(; i<kvp.length; i++){         if (kvp[i].startsWith(key + '=')) {             let pair = kvp[i].split('=');             pair[1] = value;             kvp[i] = pair.join('=');             break;         }     }      if(i >= kvp.length){         kvp[kvp.length] = [key,value].join('=');     }      // can return this or...     let params = kvp.join('&');      // reload page with new params     document.location.search = params; } 

This is approximately twice as fast as a regex or search based solution, but that depends completely on the length of the querystring and the index of any match


the slow regex method I benchmarked against for completions sake (approx +150% slower)

function insertParam2(key,value) {     key = encodeURIComponent(key); value = encodeURIComponent(value);      var s = document.location.search;     var kvp = key+"="+value;      var r = new RegExp("(&|\\?)"+key+"=[^\&]*");      s = s.replace(r,"$1"+kvp);      if(!RegExp.$1) {s += (s.length>0 ? '&' : '?') + kvp;};      //again, do what you will here     document.location.search = s; } 
like image 32
annakata Avatar answered Oct 10 '22 21:10

annakata