Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create empty URL object from scratch in JavaScript

Tags:

javascript

url

I want to manually construct URL from parts using the URL object.

However, it's constructor requires a proper URL string to be passed to it, which doesn't allow to start from empty object and build it progressively.

  1. Is there a way to overcome this limitation somehow?
  2. What caused such design decision in the first place?
like image 640
Slava Fomin II Avatar asked Apr 26 '19 12:04

Slava Fomin II


People also ask

How do I create an empty object in JavaScript?

You can use Object. create(null) for a truly empty object (at least according to the mozilla docs: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…)

How do you create a URL for an object?

In your Java program, you can use a String containing this text to create a URL object: URL myURL = new URL("http://example.com/"); The URL object created above represents an absolute URL. An absolute URL contains all of the information necessary to reach the resource in question.

How do you initialize an empty object?

Initialize Typed variable to an Empty Object in TypeScript # Use type assertions to initialize a typed variable to an empty object, e.g. const a1 = {} as Animal; . You can then set the properties on the object using dot or bracket notation.


1 Answers

You have already figured out the workaround and there is no alternative other than passing the parts in or starting with a URL and mutating it.

I'll try to answer:

What caused such design decision in the first place?

By far the most common use case for URLs was to create a URL from a URL string. Someone actually did end up asking for the API you are describing in the URL spec and discussion mostly stalled.

We have an API in Node.js for constructing URLs from parts - but that creates a string one would still need to pass to the URL constructor.

So this is likely not a bad idea and it is currently blocked on someone actually doing the work of adding that capability.

like image 145
Benjamin Gruenbaum Avatar answered Sep 18 '22 09:09

Benjamin Gruenbaum