How to get the URL and fragments in Javascript?

How to get the URL and fragments in JavaScript?

There are several ways to get the URL and fragments in Javascript. Use the built-in methods or you may use the third-party libraries to fetch, parse and validate the URLs in Javascript.

1) Use the built-in browser methods to get the URL and fragments in JavaScript

js get URL and fragments

Also read: How to create copy link input field in JavaScript?

The built-in browser methods are:

  • window.location.href
  • window.location.pathname
  • window.location.hash
  • window.location.port
  • window.location.origin

To get the current page URL using JavaScript, you can use the window.location.href property. This property returns the full URL of the current page, including the protocol (http:// or https://), the hostname, the path, and the query string.

For example, if the current page is, the window.location.href property would return

console.log(window.location.href); // Full page URL

// eg. 
console.log(window.location.pathname); // page path

// eg. /foo
console.log(window.location.hash); // The anchor part of the URL

// eg. #services
console.log(; // The host name

// eg.
console.log(window.location.origin); // The protocol, hostname and port number of the URL

// eg.
// or
// http://localhost:8888
console.log(window.location.port); // The port number

// eg. 8888, from the url (http://localhost:8888)

2) Use third-party libraries to get the URL and fragments

There are many third-party libraries that can do the same task in JavaScript, such as:

  1. URL.js
  2. Uri.js

All these libraries are used to parse and format URLs in JavaScript.


<script src=""></script>

or install it with npm:

npm i -S url-js

then import it as ES Module or CommonJS Module:

import URLJS from 'url-js'; // ESM
// or
const URLJS = require('url-js'); // CommonJS
var url = URLJS("") ->
    "protocol": "https:",
    "username": "",
    "password": "",
    "host"    : "",
    "hostname": "",
    "port"    : "",
    "pathname": "/foo",
    "search"  : "?bar=baz",
    "query"   : "bar=baz",
    "hash"    : "#services",
    "path"    : "/foo?bar=baz",
    "origin"  : "",
    "domain"  : "",
    "href"    : ""


URI.js is a URL parsing, validating, and resolving library for all JavaScript environments.

npm i uri-js

Usage of URI.js

URI.parse("uri://user:[email protected]:123/one/two.three?q1=a1&q2=a2#body");
//  scheme : "uri",
//  userinfo : "user:pass",
//  host : "",
//  port : 123,
//  path : "/one/two.three",
//  query : "q1=a1&q2=a2",
//  fragment : "body"

Now you can easily get the URL and fragments in Javascript. Which method you choose depends on your needs and preferences.

Add comment