Learn about JavaScript URL objects

Learn about JavaScript URL objects

The vanilla JavaScript URL object is used to parse, construct, normalize, and encode URLs. It provides static methods and properties to easily read and modify different components of the URL.

Creating a URL

You can create a new URL object by either passing the string URL or by providing a relative path and a base string URL to its constructor:

// url object with absolute path
const url1 = new URL('https://attacomsian.com/blog/javascript-url-object');

// url object with relative path and base url const url2 = new URL('/blog/javascript-url-object', 'https://attacomsian.com');

In the example above, both URLs are same. We can even create a new URL based on the path relative to an existing URL:

// create new url based on existing url
const url3 = new URL('/blog', url1);

console.log(url3.toString()); // https://atttacomsian.com/blog

URL Properties

The URL object is very helpful if you want to extract different parts from a string URL, such as the host name, port, relative path, and parameter values. You can access these properties immediately after the URL object is created:

const url = new URL('https://attacomsian.com/blog/javascript-url-object#url-properties');

console.log(url.protocol); // https: console.log(url.host); // attacomsian.com console.log(url.pathname); // /blog/javascript-url-object console.log(url.hash); // #url-properties console.log(url.origin); // https://attacomsian.com

In addition to the above properties, the URL object also has:

  • search — The query parameters string including the leading ? character.
  • href — The complete URL, same as url.toString() method.
  • port — Returns the port of the URL.
  • searchParams — A URLSearchParams object that can be used to access the individual query parameters found in search.
  • username & password — Only available if HTTP authentication is used.

Apart from the above properties, the URL object also provides two methods:

  • toString() — It is similar to url.href but cannot be used to modify the value.
  • toJSON() — It returns the same string as href property.

Updating a URL

The URL object properties (except origin and searchParams) can be used to construct a new URL or update parts of an existing URL:

// construct a url
const url = new URL('http://attacomsian.com');
url.pathname = '/blog/javascript-url-object';
url.hash = '#url-properties';

// update protocol property url.protocol = 'https:';

console.log(url.toString()); // https://attacomsian.com/blog/javascript-url-object#url-properties

Static Methods

The URL interface provides createObjectURL() static method to generate a blob URL (starts with blob: as its schema) that uniquely identify the object in the browser:

const blobUrl = URL.createObjectURL(blob);

Once you have the blob URL, pass it to revokeObjectURL() static method to remove it from the memory:

URL.revokeObjectURL(blobUrl);

URL Object Usage

At the moment, the URL object usage is limited. Simple strings are good enough for making network requests. However, you can use the URL object in modern JavaScript APIs especially in Fetch API, or even in XMLHttpRequest (XHR) to communicate with the server.

Here is an example of Fetch API that uses a URL object to get a JSON object:

const url = new URL('https://reqres.in/api/users');

fetch(url) .then(res => res.json()) .then(res => { res.data.map(user => { console.log(${user.id}: ${user.first_name} ${user.last_name}); }); });

Originally published by  Atta at attacomsian.com


===========================================

Thanks for reading :heart: If you liked this post, share it with all of your programming buddies! Follow me on Facebook | Twitter

Building a Simple URL Shortener With HTML and Javascript

Get URL Parameters with JavaScript

Tutorial - Using Async Await in Node.js

7 best JavaScript Design Patterns You Should Know


javascript web-development

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Hire Web Developer

Looking for an attractive & user-friendly web developer? HourlyDeveloper.io, a leading web, and mobile app development company, offers web developers for hire through flexible engagement models. You can **[Hire Web...

Why Web Development is Important for your Business

With the rapid development in technology, the old ways to do business have changed completely. A lot more advanced and developed ways are ...

Important Reasons to Hire a Professional Web Development Company

    You name the business and I will tell you how web development can help you promote your business. If it is a startup or you seeking some...

Hire Dedicated eCommerce Web Developers | Top eCommerce Web Designers

Build your eCommerce project by hiring our expert eCommerce Website developers. Our Dedicated Web Designers develop powerful & robust website in a short span of time.

How long does it take to develop/build an app?

This article covers A-Z about the mobile and web app development process and answers your question on how long does it take to develop/build an app.