Skip to main content

Javascript JS function to break a URL into its components or parts


How to break or split a given URL into various parts like Host, protocol, relative path, end file , directories etc?

A simple JS function is given below which uses window.location object to retrive parts of a url into an array.


<script>
function break_uri(){
var arr_uri = new Array();
arr_uri["FULL"] = window.location.href;
arr_uri["PROTOCOL"] = window.location.protocol;
arr_uri["HOST"] = window.location.host;
arr_uri["PATH_NAME"] = window.location.pathname;
var n = window.location.pathname.lastIndexOf('/');
var end_file=window.location.pathname.substr(n);
arr_uri["END_FILE"] = end_file;
return arr_uri;
}

How to use the above function?
var arr = break_uri();;
alert( "Absolute Url : " + arr["FULL"]);
alert( "Protocol : " + arr["PROTOCOL"]);
alert( "Host : " + arr["HOST"]);
alert( "Relative path : " + arr["PATH_NAME"]);
alert( "End File : " + arr["END_FILE"]);
</script>



If you want to break up path name to give the directory levels

var pathArray = window.location.pathname.split( '/' );

to loop through path array:

for ( i = 0; i < pathArray.length; i++ ) {
document.write( pathArray[i]);
}





If you prefer an advanced function , you can try parseUri script by Steven Levithan from stevenlevithan.com

// parseUri 1.2.2
// (c) Steven Levithan <stevenlevithan.com>
// MIT License

function parseUri (str) {
var o = parseUri.options,
m = o.parser[o.strictMode ? "strict" : "loose"].exec(str),
uri = {},
i = 14;

while (i--) uri[o.key[i]] = m[i] || "";

uri[o.q.name] = {};
uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
if ($1) uri[o.q.name][$1] = $2;
});

return uri;
};

parseUri.options = {
strictMode: false,
key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],
q: {
name: "queryKey",
parser: /(?:^|&)([^&=]*)=?([^&]*)/g
},
parser: {
strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
loose: /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
}
};



How to use the function?
var obj_url = parseUri("http://usr:pwd@www.test.com:81/dir/dir.2/index.htm?q1=0&&test1&test2=value#top");


How to parse the object?
// parsing the result object

for (var prop in obj_url) {
// important check that this is objects own property
// not from prototype prop inherited
if(obj_url.hasOwnProperty(prop)){
document.write(prop + " = " + obj_url[prop]+"<br/>");
}
}



Result looks like this

query = q1=0&&test1&test2=value
file = index.htm
directory = /dir/dir.2/
path = /dir/dir.2/index.htm
relative = /dir/dir.2/index.htm?q1=0&&test1&test2=value#top
port = 81
host = www.test.com
password = pwd
user = usr
userInfo = usr:pwd
authority = usr:pwd@www.test.com:81
protocol = http
source = http://usr:pwd@www.test.com:81/dir/dir.2/index.htm?q1=0&&test1&test2=value#top
queryKey = [object Object]

queryKey should be looped again for specify query string parameters


You can find the explanation and updated version of parseUri script at:
http://blog.stevenlevithan.com/archives/parseuri
Demo : http://stevenlevithan.com/demo/parseuri/js/

Popular posts from this blog

How to use WiFi adapter on Ubuntu 16.04 desktop PC - Realtek RTL8188EUS 802.11n Wireless USB Network Adapter Driver installation

Installation of Realtek RTL8188EUS 802.11n Wireless USB Network Adapter on Desktop PC having Ubuntu 16.04 OS My PC is running in Ubuntu 16.04 OS, recently I thought of using a dongle wife adapter to access our home's Wifi network. For this I used Realtek RTL8188EUS 802.11n Wireless USB Network Adapter ( Model No: OT-WUA950NM ) This small device cost around Rupees 250/- to Rs 300/- in India. I did the following steps for installation of this Realtek Nano Wifi Adapter: Plug Realtek RTL8188EUS 802.11n Wireless USB Network Adapter to your PC's USB port, Take the terminal application and run the command "lsusb" to list the plugged in usb devices: Myhome:~$ lsusb Bus 007 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub Bus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub Bus 006 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub Bus 005 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub Bus 001 Device 003: ID 0bda:8179 Realtek Semiconductor Corp. R...

How to delete videos from your Youtube Watch History list?

How to Delete Individual or all videos from your Youtube Watch History list? Youtube keeps a fine record of the videos that you had watched earlier. You can view this by visiting the History section. If you want to remove the video's from the list do the following: Logon to Youtube and click on the "History" tab on the left menu to view Watch History ( Read more ) There will be check boxes corresponding to each video in the list Tick the check boxes of the videos which you want to remove Click on " Remove " button to delete the videos.

ICICI prudential Customer portal updated - Option to change password is missing - Know how to change your ICICI prudential password

Recently I received an SMS from ICICI prudential asking for login to their website's customer portal using the phone number as user Id and an autogenerated one time password given in the message as password. The SMS messsage was like this. Dear ***Cust Name*** login to your policy(ies) on www.iciciprulife.com with your user id as **mobile number*** and One time use password as ***password***


Urgent Openings for PHP trainees, Andriod / IOS developers and PHP developers in Kochi Trivandrum Calicut and Bangalore. Please Send Your updated resumes to recruit.vo@gmail.com   Read more »
Member
Search This Blog