How to parse URL Using jQuery



We can simply parse the current URL elements using window.location JavaScript object. Window.location object contains information about the current URL. For example, to find out protocol in the URL, we can simply use.
var sProtocol = window.location.protocol;
But let’s say you have URL in a string variable or assigned to any DOM element like anchor tag, then window.location is not going to help you. For example, for following URL you want to parse all the elements like protocol, host name, hash, query string parameter etc.
var sURL = “http://jquerybyexample.net/codes/code-repository?id=12#top”;
In first place, you will definitely look for regex on the web to parse each element. But jQuery can help you here with very simple coding. The solution is to create a new anchor tag using the URL.
$(document).ready(function () {
    var url = 'http://jquerybyexample.net/codes/code-repository?id=12#top';
    //Create a new link with the url as its href:
    var a = $('', { href: url});
    var sResult = 'Protocol: ' + a.prop('protocol') + '
' + 'Host name: ' + a.prop('hostname') + '
' + 'Path: ' + a.prop('pathname') + '
' + 'Query: ' + a.prop('search') + '
' + 'Hash: ' + a.prop('hash'); $('span').html(sResult); });
SHARE

Nothing shocks me, I'm a Software Engineer. And I am not young enough to know everything. I live in World Wide Web and from there take care of this website. This website communicates about my work, learning and experience. I believe life is short, and it is for loving, sharing, learning and connecting. So lets connect..