How to Get URL Parameters Using JavaScript

Sometimes we have to get URL parameters using JavaScript. It is easy to get URL query string parameters using JavaScript.

JavaScript Get URL Parameter

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 in Query String

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>

Read Also: How to Get Multiple Checkbox Value in jQuery Using Array

Conclusion

I hope now you can use JavaScript to get URL parameters.

JavaScript became quite popular language in recent years due to its flexibility and cross-platform support. Also, 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 *