Skip to content

JavaScript get URL | Current URL Example code

  • by

Use window.location.href to Get Current URL With JavaScript. There are many ways to do it.

Single line code get URL with JavaScript

var href = window.location.href;

Example of how to get current URL in JavaScript

HTML example code

<!DOCTYPE HTML>
<html>

<body>

	<script>
		var href = window.location.href;
		alert(href);
	</script>
</body>
</html>					

Output:

JavaScript get URL

Another way

<script>
		var currentLocation = window.location;
		alert(currentLocation);
</script>

More to Know:

  • if you need a relative path, simply use window.location.pathname;
  • if you’d like to get the hostname, you can use window.location.hostname;
  • and if you need to get the protocol separately, use window.location.protocol
  • also, if your page has hash tag, you can get it like: window.location.hash.

So window.location.href handles all in once… basically:

Do comment if you have any doubts or suggestions on this JS URL topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading