Sometimes we have to get URL parameters using JavaScript. It is easy to get URL query string parameters using JavaScript.
Index
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.
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>
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
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 🙂
There is a reason big-name companies like CNN use WordPress. WordPress is a popular content…
In this tutorial, I'm going to show you how to install MySQL on your computer.…
Download Turbo C++ for windows 10 in just 7 Mb and run your first C++…
We can redirect any webpage to any other or redirect the whole domain or website…
There are lots of methods to redirect pages, like refresh-redirect from META tag, redirect from…
Include files in PHP are used in appending various global or config files. We can…