Get absolute URL using Javascript

Below is the simple method to get absolute URL using javascript. This code can be run on the Browser Console directly. Open the developer tools and navigate to console tab and paste the below function to test the snippet.

Sample Code Get Absolute URL using Javascript

var getAbsoluteUrl = (function() {
	var a;
	return function(url) {
		if(!a) a = document.createElement('a');
		a.href = url;
		return a.href;
	};
})();

// Sample Result based on the input.
getAbsoluteUrl('/'); //Returns https://itsmycode.com/

//Returns https://itsmycode.com/get-absolute-url-using-javascript
getAbsoluteUrl('/get-absolute-url-using-javascript');

How to read the current URI in parts?

Let us take an example of the current URL https://itsmycode.com/get-absolute-u…ing-javascript/ ‎

location.protocol = "http:"
window.location.host = "itsmycode.com"
window.location.pathname="/get-absolute-url-using-javascript/"

To get the complete URL, we can concat the above code as shown below.

var myURL = window.location.protocol + "//" + window.location.host  + window.location.pathname;
1 comment
Leave a Reply

Your email address will not be published.

Sign Up for Our Newsletters

Subscribe to get notified of the latest articles. We will never spam you. Be a part of our ever-growing community.

You May Also Like
Javascript

Scope of variables in JavaScript

What is the scope of variables in Javascript? Scope in javascript refers to the variables and the functions which are accessible and in what context it will be executed. There are…
View Post