OneBite.Dev - Coding blog in a bite size

get url in javascript

Code snippet for how to how to get url in javascript with sample and detail explanation

In this article, we’ll delve into JavaScript and explain how to retrieve a Uniform Resource Locator (URL) using the language’s features. This tutorial is aimed at helping both beginner and intermediate programmers.

Code snippet to get URL in JavaScript

 var url = window.location.href;
 console.log(url);

Code Explanation for getting URL in JavaScript

Let’s break down the snippet to comprehend how it works, step by step.

  1. var url = window.location.href;: In this line, we use the “window.location.href” property of JavaScript, which returns the entire URL of the current page. We’re storing this URL in a variable named “url”. The “window” object is a top-level object in client-side JavaScript, which represents the window in which the script is running. The “location” object is a property of the “window” object, and it holds information about the current URL. The “href” property is a part of the “location” object and stores the complete URL of the page.

  2. console.log(url);: Console.log is a function in JavaScript that is used to print any kind of variables, defined before in it, or just print any message that needs to be displayed to the user. Here it will display the stored URL when you run the code in a console of a browser.

That’s it! You have successfully retrieved the URL using JavaScript. Remember, JavaScript provides various other properties related to “location” object which can be utilised to get different parts of the URL like hostname, pathname, protocol etc. according to your requirement. You can practice with different properties to increase your understanding and effectiveness with JavaScript. Happy Coding!

javascript