Given a URL and the task is to add an additional parameter (name & value) to the URL using JavaScript.
URL.searchParams: This readonly property of the URL interface returns a URLSearchParams object providing access to the GET decoded query arguments in the URL.
Syntax:
var URLSearchParams = URL.searchParams;
Example 1: This example adds the parameter by using append method.
<!DOCTYPE HTML>
< html >
< head >
< title >
How to add a parameter to the URL
</ title >
</ head >
< body style = "text-align:center;" >
< h1 style = "color:green;" >
GeeksForGeeks
</ h1 >
< p id = "GFG_UP" style =
"font-size: 15px; font-weight: bold;" >
</ p >
< button onclick = "GFG_Fun()" >
Add Parameter
</ button >
< p id = "GFG_DOWN" style =
"color:green; font-size: 20px; font-weight: bold;" >
</ p >
< script >
var up = document.getElementById('GFG_UP');
up.innerHTML = url;
var down = document.getElementById('GFG_DOWN');
function GFG_Fun() {
url.searchParams.append('param_1', 'val_1');
down.innerHTML = url;
}
</ script >
</ body >
</ html >
|
Output:
- Before clicking on the button:

- After clicking on the button:

Example 2: This example adds the parameter by using set method.
<!DOCTYPE HTML>
< html >
< head >
< title >
How to add a parameter to the URL
</ title >
</ head >
< body style = "text-align:center;" >
< h1 style = "color:green;" >
GeeksForGeeks
</ h1 >
< p id = "GFG_UP" style =
"font-size: 15px; font-weight: bold;" >
</ p >
< button onclick = "GFG_Fun()" >
Add Parameter
</ button >
< p id = "GFG_DOWN" style =
"color:green; font-size: 20px; font-weight: bold;" >
</ p >
< script >
var up = document.getElementById('GFG_UP');
up.innerHTML = url;
var down = document.getElementById('GFG_DOWN');
function GFG_Fun() {
url.searchParams.set('param_1', 'val_1');
down.innerHTML = url;
}
</ script >
</ body >
</ html >
|
Output:
- Before clicking on the button:

- After clicking on the button:
