How to parse URI in JavaScript

May 03, 2020 No comments JavaScript Snippets Examples QA URI parse Vanilla JS

1. Introduction

In this article, we are going to show how to parse the URI in JavaScript. We will use two approaches older and modern based on a dedicated object.

2. Using document.createElement() method

The one method to parse URI and get its components in JavaScript is to create a element and assign URI as a href attribute. From that object, you can get all important URI components like protocol, port, hostname, hash, etc.


const parser = document.createElement('a');
parser.href = "https://frontbackend.com:8080/pathname/?search=test#hash";

console.log(parser.protocol); // => "https:"
console.log(parser.hostname); // => "frontbackend.com"
console.log(parser.port);     // => "8080"
console.log(parser.pathname); // => "/pathname/"
console.log(parser.search);   // => "?search=test"
console.log(parser.hash);     // => "#hash"
console.log(parser.host);     // => "frontbackend.com:8080"


3. Using URL object

The modern aproach to parse URI is to use dedicated JavaScript object URL.

This object contains the following properties:

hash a string containing the '#' followed by the fragment identifier of the URL
host a string that contains the domain followed by a ':' and the port of the URL
hostname a string containing the domain of the URL
href a stringifier that returns a string containing the whole URL
origin a string containing the origin of the URL, that is its scheme, its domain and its port
pathname a string containing an initial '/' followed by the path of the URL
port a string containing the port number of the URL
protocol a string containing the protocol scheme of the URL, including the final ':'
search a string indicating the URL's parameter string
searchParams a URLSearchParams object which can be used to access the individual query parameters found in search

There is a great similarity between the parameters of the URL object and those stored in the object that contains the current location of the document.


const url = new URL("https://frontbackend.com:8080/pathname/?search=test#hash");

console.log(url.protocol); // => "https:"
console.log(url.hostname); // => "frontbackend.com"
console.log(url.port);     // => "8080"
console.log(url.pathname); // => "/pathname/"
console.log(url.search);   // => "?search=test"
console.log(url.hash);     // => "#hash"
console.log(url.host);     // => "frontbackend.com:8080"

url.searchParams.forEach((value, key) => console.log(value, key)); // "test", "search"

4. Conclusion

In this article, we showcased how to parse URI from the string in JavaScript. We used 'old' method that creates and parse a tag and modern solution where we used new URL() object.

{{ message }}

{{ 'Comments are closed.' | trans }}