Adding a parameter to the URL with JavaScript

Lessan Vaezi picture Lessan Vaezi · Jan 28, 2009 · Viewed 629k times · Source

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.

Answer

Vianney Bajart picture Vianney Bajart · May 24, 2017

You can use one of these:

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);