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.


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

// similar behavior as clicking on a link
window.location.href = "";

Example URL:      >
window.location.hostname  >
window.location.port      > 8000
window.location.protocol  > http
window.location.pathname  > page.php
window.location.href      >
window.location.hash      > #about    > ?foo=9


Example URL:

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

Redirect to

$(location).attr('href', '');


Redirect to

$window.location.href = '';

Documentation for $location service.

comments powered by Disqus