
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Add a Parameter to the URL in JavaScript
In this article, you will understand how to add a parameter to the URL in JavaScript. There are two methods to add parameters to an url: append() method and set() method.
The append() method is used to specifically add key-value pairs to the url.
The set() method adds the value to a specific key. If the key doesn't exist, a new key is created. If several keys exist, the value is updated for one of them and others are deleted.
Example 1
Let's look at the append() method in this example
let inputUrl = new URL('https://urlExample.com?key1=value1'); let inputParams = new URLSearchParams(inputUrl.search); console.log("The parameters of the url is defined as: ", inputParams) inputParams.append('key2', 'value2'); console.log("
The url after adding adding the parameters is: ",inputParams)
Explanation
Step 1 ? Define an url with parameters.
Step 2 ? Use the append() method to add new parameters to the url.
Step 3 ? Display the result.
Example 2
Let's look at the set() method in this example
let inputUrl = new URL('https://urlExample.com?key1=value1'); let inputParams = new URLSearchParams(inputUrl.search); console.log("The parameters of the url is defined as: ", inputParams) inputParams.set('key2', 'value2'); console.log("
The url after adding adding the parameters is: ",inputParams)
Explanation
Step 1 ? Define an url with parameters.
Step 2 ? Use the append() method to add new parameters to the url.
Step 3 ? Display the result.