SoFunction
Updated on 2025-04-13

How to get the protocol, domain name, and port number of the current website

js get the protocol, domain name, and port number of the current website

In JavaScript, you can obtain the URL information of the current website through objects, including protocol, domain name, port number, etc.

Here is an example of how to obtain this information separately:

1. Obtain Protocol

The protocol part can be retrieved by this, which will return the protocol name including the colon (:), such as http: or https:.

var protocol = ;
(protocol); // Output:http: or https:

2. Get the domain name (Hostname)

The domain name part can be obtained, which will return the domain name that does not include the port number.

var hostname = ;
(hostname); // Output:For example 

3. Get the port number (Port)

The port number can be obtained through.

If the port number is not explicitly specified in the URL and the protocol is http, the port number defaults to 80; if the protocol is https, the port number defaults to 443.

However, in these cases, the default value will not be returned, but the empty string "" will be returned.

var port = ;
(port); // Output:For example 8080 or ""(If not specified and is the default port)

Example: Combining URL section

If you want to combine protocol, domain name, and port number (if not default), you can do this:

var protocol = ;
var hostname = ;
var port =  ? ':' +  : ''; // If the port number is not the default, add ':' and port numbervar baseUrl = protocol + '//' + hostname + port;
(baseUrl); // Output:For example :8080 or 

Please note:

  • This combination assumes that you want a basic URL that can be used to construct a new URL.
  • If your goal is to check or analyze the URL of the current page, the individual properties you directly access are usually sufficient.

4. Get the protocol domain name and port number together (Origin)

The port number can be obtained through.

var origin = ;
(origin); // Output::8080

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.