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

Deep-sea Anglerfish Black Seadevil Scary looking creature Video

Deep-sea Anglerfish are the strange and elusive creature that are very rarely observed in their natural habitat. Fewer than half a dozen have ever been captured on film or video by deep-diving research vehicles.They are mostly  found in tropical to temperate waters of the Indian,Pacific and Atlantic Oceans.

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...

Cheap Tourist boat service in Alapuzha - Enjoy the beauty of Aleppey Back waters using govt owned Tourist boat services

Feasible Tourist boat services in Alapuzha Aleppey / Alappuzha is one of the beautiful places in kerala. Aleppey district is famous for it amazing backwaters , you can enjoy house boat rides here. Kerala State Water transport department  (Kerala SWTD) provides facilities for tourists to enjoy the beauty of backwater by paying much less charge when compared to private boat services. There are boat services from Aleppey boat station which takes tourists to inner parts of the backwaters.


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