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 = "";
var url = new URL(str);
var name = url.searchParams.get("name");



You can use the window.location.href property which allows you to retrieve the URL of the current page.


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 = "";

var url = new URL(str);

var search_params = new URLSearchParams(; 

if(search_params.has('name')) {
	var name = search_params.get('name');


mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

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