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.
Table of Contents
1) Use the built-in browser methods to get the URL and fragments in JavaScript

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.host
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 https://example.com/foo?bar=baz, the window.location.href
property would return https://example.com/foo?bar=baz.
console.log(window.location.href); // Full page URL
// eg. https://example.com/foo?bar=baz#services
console.log(window.location.pathname); // page path
// eg. /foo
console.log(window.location.hash); // The anchor part of the URL
// eg. #services
console.log(window.location.host); // The host name
// eg. example.com
console.log(window.location.origin); // The protocol, hostname and port number of the URL
// eg. https://example.com
// 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:
- URL.js
- Uri.js
All these libraries are used to parse and format URLs in JavaScript.
URL.js
<script src="https://unpkg.com/url-js"></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("https://example.com/foo?bar=baz#services") ->
{
"protocol": "https:",
"username": "",
"password": "",
"host" : "example.com",
"hostname": "example.com",
"port" : "",
"pathname": "/foo",
"search" : "?bar=baz",
"query" : "bar=baz",
"hash" : "#services",
"path" : "/foo?bar=baz",
"origin" : "https://example.com",
"domain" : "example.com",
"href" : "https://example.com/foo?bar=baz#services"
}
URI.js
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");
//returns:
//{
// scheme : "uri",
// userinfo : "user:pass",
// host : "example.com",
// 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