How to get URL parameters in JavaScript
Using parameters in a URL is probably the easiest way to pass variables from one web page to another. In this tutorial, we will discover how to retrieve the parameters of a URL with JavaScript.
Method 1: Using the URL object
Since the following code works in a web browser, you can use the URL object (which is part of the APIs provided by browsers that support JavaScript):
var str = "http://stackhowto.com/t.html?name=alex-babtise&age=25&address=paris"; var url = new URL(str); var name = url.searchParams.get("name"); console.log(name);
Output:
alex-babtise
You can use the window.location.href property which allows you to retrieve the URL of the current page.
[st_adsense]
Method 2: Checking if the parameter exists in the URL
has() method can be used to check if the parameter exists in the URL. It returns true if the parameter exists, otherwise it returns false.
If the parameter exists, its value can be found via the get method.
var str = "http://stackhowto.com/t.html?name=alex-babtise&age=25&address=paris"; var url = new URL(str); var search_params = new URLSearchParams(url.search); if(search_params.has('name')) { var name = search_params.get('name'); console.log(name) }
Output:
alex-babtise[st_adsense]