Smart way JavaScript to get absolute URL address of hyperlink

  • 2021-06-28 10:38:54
  • OfStack

Handling simple URL formats can be a nightmare for Web programmers.Imagine that a web address has many components that affect how you interpret it:

Whether <} starts with a/character
Whether <} starts with //
Whether < < < 63;Beginning of number
Whether <} starts with the #
...etc.
When you want the absolute address of this address, how do you decide to process and parse it?It may be http or https.Enough headache.Fortunately, we have a simple way to determine its absolute address by creating an A element to assist with this task!

JavaScript Code

Here I'll use an JavaScript function that returns a function, which has many benefits, as described below.


var getAbsoluteUrl = (function() {
 var a;

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

 return a.href;
 };
})();

This function looks a bit complicated. It assigns a function to a variable first, and there is another function and a predefined variable in this function.One might ask why a function should be embedded and whether it can be simplified as follows:


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

Of course, this simple writing can't be wrong, but it's not perfect because embedding a function increases the complexity of the code, but it ensures that the A element is created only once and can be reused, saving time and memory.

Another question might be asked, wondering why an if judgment is needed in the nested second function, and why not write it like this:


var getAbsoluteUrl = (function() {
 var a = document.createElement('a');

 return function(url) {
 a.href = url;

 return a.href;
 };
})();

This is naturally a working writing style, and there are no errors in the functionality.However, subtly, without an if statement, the A element is initialized even if the function is not called by any code when it is defined, and with an if statement, the A element is created only when it is actually used, without wasting memory and CPU.

Well, with this method, whatever URL address you pass in, it returns the absolute address.

Let's give it a try!


Related articles: