Get URL Parameters with JavaScript

Suppose we search for google translator, and we get https://www.google.com/search?q=google+translator&oq=google+transla&aqs=chrome in the address bar. This is the URL that has two parts; the first part indicates the website address https://www.google.com/ and the rest part that …

Get URL Parameters with JavaScript

Suppose we search for google translator, and we get https://www.google.com/search?q=google+translator&oq=google+transla&aqs=chrome in the address bar. This is the URL that has two parts; the first part indicates the website address https://www.google.com/ and the rest part that is separated by a question mark “?” are URL parameters. In this article, we are accessing the URL parameters by using JavaScript.

What is the URL parameter in JavaScript?

URL parameter that is also called query string, is the method to transfer valuable data that can be queries, information, product name, item number, etc., from page to page or from client to server. When we search and click on a particular link, we see URL parameters are created in the address bar, and this is because clicking on a specific link will show you filtered results in the following tab. URL parameters indicate that what you have searched for is processed.

How to get URL parameters using JavaScript?

There are two methods to get URL parameters in JavaScript.

1. Use window.location.search to get the values of parameters inside the console.

Enter this link in your browser: 

https://drasticcode.com/?website=DrasticCode&num=3984&str=HelloWorld!

Open the console tab and type the below code.

The below code returns the current query string from the URL that returns query after question mark except for the hash sign(if it is present in the query string).

const queryString = window.location.search;
console.log(queryString);

URLSearchParams(): is a constructor that allows using the convenient method for search parameters and returns an object instance.

const urlParams = new URLSearchParams(queryString);

Operations that can perform on URL parameters.

  1. URLSearchParams.get(): It gets the first value of the key from the specified search parameters.
const website = urlParams.get('website')
console.log(website);
//DrasticCode
const num = urlParams.get('num')
console.log(num);
//3984
const str = urlParams.get('str')
console.log(str);
//HelloWorld!

For example:

Get URL Parameters with JavaScript

2. URLSearchParms.has(): it checks out the parameter list and returns the Boolean output that specified parameter exists or not in the parameters.

console.log(urlParams.has('website'));
// true
Get URL Parameters with JavaScript

3. URLSearchParams.append(): it adds new key/value pair in the search parameter Syntax

urlParams.append(key, value);

urlParams.append('item', 4);

4. URLSearchParams.delete(): Delete method removes all search parameters and all their concerned values.

urlParams.delete('item');

5. URLSearchParams.key(): By using an iterator, it returns all keys of the object.

const urlParams = new URLSearchParams(queryString);
const keys = urlParams.keys();
for (const key of keys) console.log(key);
//website
//num
// str
Get URL Parameters with JavaScript
Data transfer from client to server via URL address contains URL Parameters. In JavaScript, the URLSearchParams interface helps to Get URL parameters in the console.

6. URLSearchParams.values(): By using an iterator, it returns all values of keys that exist include in the object.

const values = urlParams.values()
undefined
for (const value of values) console.log(value);
//DrasticCode
//3984
//HelloWorld!
Get URL Parameters with JavaScript

7. URLSearchParams.entries(): By using an iterator, it returns all key/value pairs that exist in the object.

const entries = urlParams.entries();
for(const entry of entries) {
  console.log(`${entry[0]}: ${entry[1]}`);
}
Get URL Parameters with JavaScript

8. URLSerachParams.sort(): Sort operation performs the sort on key/value pairs in the object and returns the sorting order according to Unicode points by using the standard sorting algorithm.

urlParams.sort();
console.log(urlParams.toString());
Get URL Parameters with JavaScript

2. Use the URLsearchParams function in a file to get values of the parameter.

URLSearchParams is a constructor that allows the method to work with the URL query string. We can use the search params property to return a URLSearchParams object. 

First, create a string that can only get URL parameters that are separated by “?” from the website address. Use split() that split parameters from website addresses by using assigned signs. These split parameters are stored in the paramString variable and pass that variable from the URLSearchParams constructor.

The Object. entries() method returns an iterator that contains both keys and their values that exist in the object. 

The Key is left of the equal sign, and the value contained by the key is on the right side of the equal sign. Key is defined by 0, and value is by 1. Two different keys are separated by the ampersand “&” symbol.

let paramString = urlString.split('?')[1];
let queryString = new URLSearchParams(paramString);
for (let pair of queryString.entries()) {
	console.log("Key is: " + pair[0]);
	console.log("Value is: " + pair[1]);
}

Coding Example:

<body><center>
	<h1 style="color:orange;">
		DrasticCode
	</h1>
	 <h2 style="color: blue;">URLSearchParam Object </h2>
	<h3><b>
		 Getting URL Parameters With JavaScript
	</b></h3>
	<p>
		Click Button to get the URL parameters in the console Tab.
	</p>
	<p>
		Pres Crtl+Shift+i to open the console tab
	</p>
	<p>
		URL that is used to operate : https://www.DrasticCode.com/homepage.php?%20x=DasticCode&y=3984&z=Hello%20Worlds!
	</p>
	<button onclick="getParameters()">
		Get URL parameters
	</button>
	<script>
		function getParameters() {
           let urlString ="https://www.example.com/homepage.php?x=DrasticCode&y=3984&z=Hello Worlds!";
          let paramQuery = urlString.split('?')[1];
	    let queryString = new URLSearchParams(paramQuery);
		    for (let pair of queryString.entries()) {
				console.log("Key:" + pair[0]);
				console.log("Value:" + pair[1]);
			}
		}
	</script>
	</center>
</body>

Output

Conclusion

In this article, we discussed how to get URL parameters in JavaScript. We get the queries in the tab from the address bar and perform the different operations on it. We create a defined link and perform the direct operation through the program to get their values in the console tab by just clicking a button.

Suggested Read: Remove Brackets from list Python

Leave a Comment