2

I want to read the port of an string of an url I have. I found out that you can create a new URL-object with the urlstring as an argument. Then you can call the port property of that object to get the port of the urlstring.

The port of my url is 443. If I give a string with 443 as the port into the URL-object, the port-property of the url-object is "". If I choose other numbers as the port it works fine.

Does anyone know why this is happening?

Here is a code-snippet:

const URL_STRING1 = "https://example.com:443/";

let url1 = new URL(URL_STRING1);
console.log(url1.port);

const URL_STRING2 = "https://example.com:442/";

let url2 = new URL(URL_STRING2);
console.log(url2.port);

const URL_STRING3 = "https://example.com:444/";

let url3 = new URL(URL_STRING3);
console.log(url3.port);
Code Maniac
  • 37,143
  • 5
  • 39
  • 60
IceRevenge
  • 1,451
  • 18
  • 33

3 Answers3

1

443 is default port for https

URL reference for full specs

....
--->   Set url’s port to null, if port is url’s scheme’s default port, and to port otherwise.
                                                ^^^^^^^^^^^^^^^^^^^^^
....

Default scheme reference for full specs

A special scheme is a scheme listed in the first column of the following table. A default port is a special scheme’s optional corresponding port and is listed in the second column on the same row.

scheme  port
"ftp"   21
"file"  
"http"  80
"https"     443
"ws"    80
"wss"   443 
Code Maniac
  • 37,143
  • 5
  • 39
  • 60
0

This object is an experimental one, so you can trsut on it. Use a simple regex to extract the port -

const URL_STRING1 = "https://example.com:443/";
console.log(URL_STRING1.match(/https:\/\/example\.com:(?<=:)(\d{3})/));
0

This unobvious observation seems to be mentioned in the javascript documentation:

Note: If an input string passed to the URL() constructor doesn't contain an explicit port number (e.g., https://localhost) or contains a port number that's the default port number corresponding to the protocol part of the input string (e.g., https://localhost:443), then in the URL object the constructor returns, the value of the port property will be the empty string: ''.

Source: https://developer.mozilla.org/en-US/docs/Web/API/URL/port

neowulf33
  • 635
  • 2
  • 7
  • 19