Получить протокол, домен и порт из URL - PullRequest
272 голосов
/ 04 августа 2011

Мне нужно извлечь полный протокол, домен и порт из заданного URL. Например:

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

Ответы [ 16 ]

2 голосов
/ 09 сентября 2016
var getBasePath = function(url) {
    var r = ('' + url).match(/^(https?:)?\/\/[^/]+/i);
    return r ? r[0] : '';
};
2 голосов
/ 02 июля 2013
var http = location.protocol;
var slashes = http.concat("//");
var host = slashes.concat(window.location.hostname);
1 голос
/ 28 апреля 2019

Вот решение, которое я использую:

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

РЕДАКТИРОВАТЬ:

Чтобы добавить кросс-браузерную совместимость, используйте следующее:

const result = `${ window.location.protocol }//${ window.location.hostname + (window.location.port ? ':' + window.location.port: '') }`;
0 голосов
/ 11 апреля 2019

Простой ответ, который работает для всех браузеров:

let origin;

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

origin = window.location.origin;
0 голосов
/ 09 сентября 2018

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

0 голосов
/ 20 августа 2018

Стиль ES6 с настраиваемыми параметрами.

/**
 * 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
}
...