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

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

Thursday, March 27, 2014


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/



How to link to this page?
If you wish to link to this page from your website, simply Copy and paste the above HTML code to your web page. It will appear on your page as:
Javascript JS function to break a URL into its components or parts.




Share this!




comments powered by Disqus

This Weeks 7 Popular Posts


Subscribe to Recent Posts by Email
Stay connected to CROZOOM with regular Email notices of new Techie articles and IT Jobs. Updates will be delivered to your Inbox as soon as they are posted online.

Enter Your Email Address:  

Delivered by FeedBurner   RSS Feed

Search this Blog   



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 »