How to usethe append method in Javascript
In this approach, we can use the URLSearchParams
interface to easily append or set parameters to a URL. The append
method allows us to add a new parameter to the existing set.
Example: This example adds the parameter by using the append method. This HTML document displays a webpage with a button. When the button is clicked, the JavaScript function GFG_Fun()
appends a new parameter (‘param_1’ with the value ‘val_1’) to the URL and updates the displayed URL accordingly.
html
<!DOCTYPE HTML> < html > < head > < title > How to add a parameter to the URL </ title > </ head > < body style = "text-align:center;" > < h1 style = "color:green;" > w3wiki </ h1 > < p id = "GFG_UP" style = "font-size: 15px; font-weight: bold;" > </ p > < button style = "cursor: pointer;" onclick = "GFG_Fun()" > Add Parameter </ button > < p id = "GFG_DOWN" style = "color:green; font-size: 20px; font-weight: bold;" > </ p > < script > let up = document.getElementById('GFG_UP'); let url = new URL("https://www.w3wiki.org"); up.innerHTML = url; let down = document.getElementById('GFG_DOWN'); function GFG_Fun() { url.searchParams.append('param_1', 'val_1'); down.innerHTML = url; } </ script > </ body > </ html > |
Output:
How to add a parameter to the URL in JavaScript ?
Given a URL the task is to add parameter (name & value) to the URL using JavaScript.
URL.searchParams: This read-only property of the URL interface returns a URLSearchParams object providing access to the GET-decoded query arguments in the URL.
Table of Content
- Using the append method
- Using set method