How to work with location url in JavaScript, jQuery, AngularJS

The location object contains information about the current URL. The location object is part of the window object and is accessed through the window.location property.

JavaScript

Location Object Properties

Property Description
hash Sets or returns the anchor part (#) of a URL
host Sets or returns the hostname and port number of a URL
hostname Sets or returns the hostname of a URL
href Sets or returns the entire URL
origin Returns the protocol, hostname and port number of a URL
pathname Sets or returns the path name of a URL
port Sets or returns the port number of a URL
protocol Sets or returns the protocol of a URL
search Sets or returns the querystring part of a URL

Location Object Methods

Method Description
assign() Loads a new document
reload() Reloads the current document
replace() Replaces the current document with a new one

The replace() method replaces the current document with a new one.

// similar behavior as an HTTP redirect
location.replace("http://newurl.com");

// similar behavior as clicking on a link
window.location.href = "http://newurl.com";

Example URL: http://www.example.com:8000/page.php#about?foo=9

window.location.host      > www.example.com:8000
window.location.hostname  > www.exmaple.com
window.location.port      > 8000
window.location.protocol  > http
window.location.pathname  > page.php
window.location.href      > http://www.example.com:8000/page.php#about
window.location.hash      > #about
window.location.search    > ?foo=9

jQuery

Example URL: http://www.example.com:8000/page.php#about?foo=9

$(location).attr('host');      > www.example.com:8000
$(location).attr('hostname');  > www.example.com
$(location).attr('port');      > 8000
$(location).attr('protocol');  > http
$(location).attr('pathname');  > page.php
$(location).attr('href');      > http://www.example.com:8000/page.php#about
$(location).attr('hash');      > #about
$(location).attr('search');    > ?foo=9

Redirect to http://proft.me

$(location).attr('href', 'http://proft.me');

AngularJS

Redirect to http://proft.me

$window.location.href = 'http://proft.me';

Documentation for $location service.

comments powered by Disqus