Skip to content

Instantly share code, notes, and snippets.

@shalotelli
Created January 30, 2014 17:34
Show Gist options
  • Save shalotelli/8714101 to your computer and use it in GitHub Desktop.
Save shalotelli/8714101 to your computer and use it in GitHub Desktop.
Javascript base_url
// return current page url
function current_url()
{
return window.location.href;
}
// return current page path
function current_path()
{
return window.location.pathname;
}
// return current page protocol
function get_protocol()
{
return window.location.protocol;
}
// return any page anchors
function get_hash()
{
return window.location.hash;
}
// return current page host
function get_host()
{
return window.location.host;
}
// return current page hostname
function get_hostname()
{
return window.location.hostname;
}
// return current page port
function get_port()
{
return window.location.port;
}
// return any GET variables
function get_query_string()
{
return window.location.search;
}
// returns the current site URL
// TODO: Check for ip6
function base_url(ext)
{
var ret_url = '',
url = current_url(),
base = url.substring(0, url.indexOf('/', 14));
// Base URL for localhost or IP
if(base.indexOf(get_protocol()+'//localhost') != -1 || is_ip4(base.replace(get_protocol()+'//', ''))) {
var pathname = current_path();
var index1 = url.indexOf(pathname);
var index2 = url.indexOf("/", index1 + 1);
var base_local_url = url.substr(0, index2);
ret_url = base_local_url + "/";
} else {
// Root URL for domain name
ret_url = base + "/";
}
if(ext !== undefined && ext !== '') {
ret_url += ext;
}
return ret_url;
}
// check if url is IPv4
function is_ip4(s)
{
var match = s.match(/^(\d+)\.(\d+)\.(\d+)\.(\d+)$/);
return match !== null &&
match[1] <= 255 && match[2] <= 255 &&
match[3] <= 255 && match[4] <= 255;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment