[javascript] Get protocol, domain, and port from URL

I need to extract the full protocol, domain, and port from a given URL. For example:

https://localhost:8181/ContactUs-1.0/contact?lang=it&report_type=consumer
>>>
https://localhost:8181

This question is related to javascript url dns protocols port

The answer is


var http = location.protocol;
var slashes = http.concat("//");
var host = slashes.concat(window.location.hostname);

host

var url = window.location.host;

returns localhost:2679

hostname

var url = window.location.hostname;

returns localhost


window.location.origin will be enough to get the same.


None of these answers seem to completely address the question, which calls for an arbitrary url, not specifically the url of the current page.

Method 1: Use the URL API (caveat: no IE11 support)

You can use the URL API (not supported by IE11, but available everywhere else).

This also makes it easy to access search params. Another bonus: it can be used in a Web Worker since it doesn't depend on the DOM.

const url = new URL('http://example.com:12345/blog/foo/bar?startIndex=1&pageSize=10');

Method 2 (old way): Use the browser's built-in parser in the DOM

Use this if you need this to work on older browsers as well.

//  Create an anchor element (note: no need to append this element to the document)
const url = document.createElement('a');
//  Set href to any path
url.setAttribute('href', 'http://example.com:12345/blog/foo/bar?startIndex=1&pageSize=10');

That's it!

The browser's built-in parser has already done its job. Now you can just grab the parts you need (note that this works for both methods above):

//  Get any piece of the url you're interested in
url.hostname;  //  'example.com'
url.port;      //  12345
url.search;    //  '?startIndex=1&pageSize=10'
url.pathname;  //  '/blog/foo/bar'
url.protocol;  //  'http:'

Bonus: Search params

Chances are you'll probably want to break apart the search url params as well, since '?startIndex=1&pageSize=10' isn't too useable on its own.

If you used Method 1 (URL API) above, you simply use the searchParams getters:

url.searchParams.get('startIndex');  // '1'

Or to get all parameters:

function searchParamsToObj(searchParams) {
  const paramsMap = Array
    .from(url.searchParams)
    .reduce((params, [key, val]) => params.set(key, val), new Map());
  return Object.fromEntries(paramsMap);
}
searchParamsToObj(url.searchParams);
// -> { startIndex: '1', pageSize: '10' }

If you used Method 2 (the old way), you can use something like this:

// Simple object output (note: does NOT preserve duplicate keys).
var params = url.search.substr(1); // remove '?' prefix
params
    .split('&')
    .reduce((accum, keyval) => {
        const [key, val] = keyval.split('=');
        accum[key] = val;
        return accum;
    }, {});
// -> { startIndex: '1', pageSize: '10' }

Here is the solution I'm using:

const result = `${ window.location.protocol }//${ window.location.host }`;

EDIT:

To add cross-browser compatibility, use the following:

const result = `${ window.location.protocol }//${ window.location.hostname + (window.location.port ? ':' + window.location.port: '') }`;

With ES6 template literals:

_x000D_
_x000D_
const url = `${location.protocol}//${location.hostname}${location.port?':'+location.port:''}`;

document.getElementById("result").innerText = url;
_x000D_
<div id="result"></div>
_x000D_
_x000D_
_x000D_


Try use a regular expression (Regex), which will be quite useful when you want to validate / extract stuff or even do some simple parsing in javascript.

The regex is :

/([a-zA-Z]+):\/\/([\-\w\.]+)(?:\:(\d{0,5}))?/

Demonstration:

function breakURL(url){

     matches = /([a-zA-Z]+):\/\/([\-\w\.]+)(?:\:(\d{0,5}))?/.exec(url);

     foo = new Array();

     if(matches){
          for( i = 1; i < matches.length ; i++){ foo.push(matches[i]); }
     }

     return foo
}

url = "https://www.google.co.uk:55699/search?q=http%3A%2F%2F&oq=http%3A%2F%2F&aqs=chrome..69i57j69i60l3j69i65l2.2342j0j4&sourceid=chrome&ie=UTF-8"


breakURL(url);       // [https, www.google.co.uk, 55699] 
breakURL();          // []
breakURL("asf");     // []
breakURL("asd://");  // []
breakURL("asd://a"); // [asd, a, undefined]

Now you can do validation as well.


window.location.protocol + '//' + window.location.host


Simple answer that works for all browsers:

let origin;

if (!window.location.origin) {
  origin = window.location.protocol + "//" + window.location.hostname + 
     (window.location.port ? ':' + window.location.port: '');
}

origin = window.location.origin;

The protocol property sets or returns the protocol of the current URL, including the colon (:).

This means that if you want to get only the HTTP/HTTPS part you can do something like this:

var protocol = window.location.protocol.replace(/:/g,'')

For the domain you can use:

var domain = window.location.hostname;

For the port you can use:

var port = window.location.port;

Keep in mind that the port will be an empty string if it is not visible in the URL. For example:

If you need to show 80/443 when you have no port use

var port = window.location.port || (protocol === 'https' ? '443' : '80');

ES6 style with configurable parameters.

/**
 * Get the current URL from `window` context object.
 * Will return the fully qualified URL if neccessary:
 *   getCurrentBaseURL(true, false) // `http://localhost/` - `https://localhost:3000/`
 *   getCurrentBaseURL(true, true) // `http://www.example.com` - `https://www.example.com:8080`
 *   getCurrentBaseURL(false, true) // `www.example.com` - `localhost:3000`
 *
 * @param {boolean} [includeProtocol=true]
 * @param {boolean} [removeTrailingSlash=false]
 * @returns {string} The current base URL.
 */
export const getCurrentBaseURL = (includeProtocol = true, removeTrailingSlash = false) => {
  if (!window || !window.location || !window.location.hostname || !window.location.protocol) {
    console.error(
      `The getCurrentBaseURL function must be called from a context in which window object exists. Yet, window is ${window}`,
      [window, window.location, window.location.hostname, window.location.protocol],
    )
    throw new TypeError('Whole or part of window is not defined.')
  }

  const URL = `${includeProtocol ? `${window.location.protocol}//` : ''}${window.location.hostname}${
    window.location.port ? `:${window.location.port}` : ''
  }${removeTrailingSlash ? '' : '/'}`

  // console.log(`The URL is ${URL}`)

  return URL
}

For some reason all the answers are all overkills. This is all it takes:

window.location.origin

More details can be found here: https://developer.mozilla.org/en-US/docs/Web/API/window.location#Properties


var getBasePath = function(url) {
    var r = ('' + url).match(/^(https?:)?\/\/[^/]+/i);
    return r ? r[0] : '';
};

Indeed, window.location.origin works fine in browsers following standards, but guess what. IE isn't following standards.

So because of that, this is what worked for me in IE, FireFox and Chrome:

var full = location.protocol+'//'+location.hostname+(location.port ? ':'+location.port: '');

but for possible future enhancements which could cause conflicts, I specified the "window" reference before the "location" object.

var full = window.location.protocol+'//'+window.location.hostname+(window.location.port ? ':'+window.location.port: '');

As has already been mentioned there is the as yet not fully supported window.location.origin but instead of either using it or creating a new variable to use, I prefer to check for it and if it isn't set to set it.

For example;

if (!window.location.origin) {
  window.location.origin = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ':' + window.location.port: '');
}

I actually wrote about this a few months back A fix for window.location.origin


Why not use:

let full = window.location.origin

var full = location.protocol+'//'+location.hostname+(location.port ? ':'+location.port: '');

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to url

What is the difference between URL parameters and query strings? Allow Access-Control-Allow-Origin header using HTML5 fetch API File URL "Not allowed to load local resource" in the Internet Browser Slack URL to open a channel from browser Getting absolute URLs using ASP.NET Core How do I load an HTTP URL with App Transport Security enabled in iOS 9? Adding form action in html in laravel React-router urls don't work when refreshing or writing manually URL for public Amazon S3 bucket How can I append a query parameter to an existing URL?

Examples related to dns

How is VIP swapping + CNAMEs better than IP swapping + A records? ping: google.com: Temporary failure in name resolution What's the source of Error: getaddrinfo EAI_AGAIN? How do I solve the "server DNS address could not be found" error on Windows 10? Creating self signed certificate for domain and subdomains - NET::ERR_CERT_COMMON_NAME_INVALID How to force DNS refresh for a website? ssh: Could not resolve hostname [hostname]: nodename nor servname provided, or not known How to filter wireshark to see only dns queries that are sent/received from/by my computer? How can I list ALL DNS records? How to redirect DNS to different ports

Examples related to protocols

What is the technology behind wechat, whatsapp and other messenger apps? Difference between Pragma and Cache-Control headers? How can I send and receive WebSocket messages on the server side? Get protocol, domain, and port from URL Difference between TCP and UDP? Which Protocols are used for PING? How does the communication between a browser and a web server take place? How does DHT in torrents work? What is the difference between DTR/DSR and RTS/CTS flow control? How do I create my own URL protocol? (e.g. so://...)

Examples related to port

Docker - Bind for 0.0.0.0:4000 failed: port is already allocated How do I kill the process currently using a port on localhost in Windows? Node.js Port 3000 already in use but it actually isn't? Can't connect to Postgresql on port 5432 Spring Boot - How to get the running port Make docker use IPv4 for port binding How to change the default port of mysql from 3306 to 3360 Open firewall port on CentOS 7 Unable to launch the IIS Express Web server, Failed to register URL, Access is denied XAMPP Port 80 in use by "Unable to open process" with PID 4