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

What are the Income Tax Rates for Indian citizens for Financial Year 2017-2018?

Income Tax Slab and Rates given below are for Indian citizens of age less than 60. This rates are applicable for the Financial Year 2017-2018 Income Tax Slab Rates Financial Year 2017-2018 Assessment Year 2018-19 Income Tax Slab Rates SLAB 1 Individuals whose total income not exceeding Rs. 2,50,000 ( 2.5 lakhs ) They are exempted from paying income tax.


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