How to Get URL Parameters Using JavaScript

We can get values of URL parameters using the searchParams object in JavaScript.

Here we are going to learn some main methods to get various parameters from the URL.

Get Single Parameter

We can get the value of a single parameter using the get() method.

Example

<!DOCTYPE html>
<html>
<body>

<script>
var url = new URL('http://example.com?name=nick');
// use window.location.href to get the current page URL in live project

var params = url.searchParams; 

var name = params.get('name');

alert("Hello " + name);
</script>

</body>
</html>

Get All Parameters

We can get all parameters in the URL using the getAll() method. The getAll() method will return an array of values of all URL parameters.

Example

<!DOCTYPE html>
<html>
<body>

<script>
var url = new URL('http://example.com?id=404&name=nick');
// use window.location.href to get the current page URL in live project

var params = url.searchParams; 

params.forEach(function(value, key) {
	document.write(key + '=' + value);
});
</script>

</body>
</html>

Check if Parameter Is Available or Not

We can check if any required parameter is available or not in the URL using the has() method.

Example

<!DOCTYPE html>
<html>
<body>

<script>
var url = new URL('http://example.com?id=404&name=nick');
// use window.location.href to get the current page URL in live project

var params = url.searchParams; 

if(params.has('number')){
	alert(number);
}else{
	alert("Given parameter is not available in the URL");
}
</script>

</body>
</html>

Conclusion

I hope now you can get all parameters of URL using JavaScript.

JavaScript became quite popular language in recent years due to its flexibility and cross-platform support. There are lots of frameworks available which are based on javascript. So, keep exploring JavaScript, and you will also feel the power of JavaScript.

Enjoy Scripting 🙂

 

Leave a Reply

Your email address will not be published. Required fields are marked *