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

Strange problem occured while trying to create a CSV file using PHP Script - The file is not seen on FTP but can download using file's absolute path url

Strange problem occured while trying to create a CSV file - The file is not seen on FTP but can download using file's absolute path url Last day I came across a strange problem when I tried to create a csv file on therver using a PHP script. the script was simply writing a given content as a csv file. The file will be created runtime. What happened was, The script executed fine, file handler for new file was created and contents was wrote into the file using fwrite and it returned the number of bytes that was written.

How to get the Query string of a URL using the Javascript (JS)?

JS function get the Query string of a URL or value of each parameter using the Javascript(JS)? If you want to get your current page's url var my_url=document.location; to get the query string part of the url use like this: var my_qry_str= location.search; this will return the part of the url starting from "?" following by query string Lets assume that your current page url is http://www.crozoom.com/2013/page.html?qry1=A&qry2=B then the location.search function will return " ?qry1=A&qry2=B " to exclue "?", do like this:


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