Skip to content

September 10, 2015

1

Parse URL JavaScript

Parsing of URL is an easy thing for any of web browser because it’s basic functionality. Instead of going deep into regular expressions for parsing of URL strings we can use the specific functionality of browser to achieve the same goals.

The basic idea of creating JavaScript function for parsing a URL is based on the ability of a browser to get seven parameters from the ‘href’ attribute of any link. These parameters are the protocol, hostname, port, pathname, search, hash, host.

To check that we can create a link, set the ‘href’ attribute with test URL and render in console all available properties for this link. There are a lot of properties and methods, but across them we can found 7, which were mentioned before:

var parser = document.createElement('a');
parser.href = 'http://example.com:3000/pathname/?search=test#hash';
for(property in parser) {
	console.log(property + ': ' + parser[property]);    
}

After execution of this script you will be able to see a lot of lines in console, but basically we need only few of them:

protocol: http:
username: 
password: 
host: example.com:3000
hostname: example.com
port: 3000
pathname: /pathname/
search: ?search=test
hash: #hash

Basically we’ve, that we have all necessary information in the ‘parser’ object. Let’s build a function which will parse URL. Let’s name it ‘parseURL’, and pass one parameter ‘URL’:

function parseURL(URL) {}

Good practice is to check if this parameter is not empty, so we will add some basic validation:

function parseURL(URL) {
    // Check if URL is not empty
    if(URL === undefined || URL === null || URL.length === 0) {
     	return;   
    }
}

Now, we can take the same approach and create link element and new empty object which will be filled with data from the link, which will be with passed to function URL. For creating an empty object the best option is using literal syntax:

	// Create a link in memory
	var parser = document.createElement('a');
    // Set attribute to parameter to make an object which URL can be automatically parsed by browser
    parser.href = URL;
    // Prepare an empty object for storing parsed parameters
    var parsedURLObject = {};

Next thing, what we need is to have an array with all seven properties which we can take from link, so let’s create an array with names of such properties:

    // Make an array with list of names of available parameters which can be taken from given URL
    var urlParts = ['protocol', 
                    'hostname', 
                    'port', 
                    'pathname', 
                    'search', 
                    'hash', 
                    'host'];

It seems that we have all we need to fill our empty object with data and return it. First is the loop where we can set all the property names and their values, using ‘urlParts’ array and actual ‘parser’ object:

    // Go through an array with names of parameters
    for(part in urlParts) {
        // Set property with name taken from an array
        // to a value from 'parser' object which was automatically filled by browser
        parsedURLObject[urlParts[part]] = parser[urlParts[part]];
    }
    // return object with all parameters filled from 'parser' object
    return parsedURLObject;

After that, we can call our function and one of parsed link specific property as simple as this example:

// Now you can choose one of seven available parameters
console.log(parseURL('http://example.com:3000/pathname/?search=test#hash').hostname);

Full source code of parse URL javascript solution below:

function parseURL(URL) {
    // Check if URL is not empty
    if(URL === undefined || URL === null || URL.length === 0) {
     	return;   
    }
 
    // Create a link in memory
    var parser = document.createElement('a');
    // Set attribute to parameter to make an object which URL can be automatically parsed by browser
    parser.href = URL;
    // Prepare an empty object for storing parsed parameters
    var parsedURLObject = {};
    // Make an array with list of names of available parameters which can be taken from given URL
    var urlParts = ['protocol', 
                    'hostname', 
                    'port', 
                    'pathname', 
                    'search', 
                    'hash', 
                    'host'];
    // Go through an array with names of parameters
    for(part in urlParts) {
        // Set property with name taken from an array
        // to a value from 'parser' object which was automatically filled by browser
        parsedURLObject[urlParts[part]] = parser[urlParts[part]];
    }
    // return object with all parameters filled from 'parser' object
    return parsedURLObject;
}
 
// Now you can choose one of seven available parameters
console.log(parseURL('http://example.com:3000/pathname/?search=test#hash').hostname);
Read more from Front End
  • Dozcent

    Nice trick over “location” object…