IT

URL에서 프로토콜, 도메인 및 포트 가져 오기

lottoking 2020. 3. 21. 10:47

URL에서 프로토콜, 도메인 및 포트 가져 오기


주어진 URL에서 전체 프로토콜, 도메인 및 포트를 추출해야합니다. 예를 들면 다음과 같습니다.

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

먼저 현재 주소를 얻으십시오

var url = window.location.href

그런 다음 해당 문자열을 구문 분석하십시오.

var arr = url.split("/");

귀하의 URL은 다음과 같습니다

var result = arr[0] + "//" + arr[2]

도움이 되었기를 바랍니다


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

이 답변 중 어느 것도 질문을 완전히 다루지 않는 것 같습니다.이 페이지는 특히 현재 페이지의 URL이 아닌 임의의 URL을 요구합니다.

방법 1 : URL API 사용 (캐비티 : IE11 지원 안 함)

URL API를 사용할 수 있습니다 (IE11에서는 지원되지 않지만 다른 곳에서는 사용 가능 ).

또한 검색 매개 변수에 쉽게 액세스 할 수 있습니다 . 또 다른 보너스 : DOM에 의존하지 않기 때문에 웹 워커에서 사용할 수 있습니다.

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

방법 2 (구식) : DOM에서 브라우저의 내장 구문 분석기 사용

구형 브라우저에서도 작동하려면 이것을 사용하십시오.

//  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');

그게 다야!

브라우저의 내장 파서가 이미 작업을 완료했습니다. 이제 필요한 부분 만 잡을 수 있습니다 (위의 두 가지 방법 모두에서 작동 함).

//  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:'

보너스 : 검색 매개 변수

'? startIndex = 1 & pageSize = 10'자체만으로는 사용할 수 없으므로 검색 URL 매개 변수를 분리 할 수도 있습니다.

위의 방법 1 (URL API)을 사용한 경우 searchParams 게터를 사용하면됩니다.

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

또는 모든 매개 변수를 얻으려면 :

Array
    .from(url.searchParams)
    .reduce((accum, [key, val]) => {
        accum[key] = val;
        return accum;
    }, {});
// -> { startIndex: '1', pageSize: '10' }

방법 2 (구식)를 사용한 경우 다음과 같이 사용할 수 있습니다.

// 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' }

어떤 이유로 든 모든 대답은 모두 과잉입니다. 이것이 전부입니다 :

window.location.origin

자세한 내용은 https://developer.mozilla.org/en-US/docs/Web/API/window.location#Properties 에서 확인할 수 있습니다.


이미 언급했듯이 아직 완전히 지원되지는 window.location.origin않지만 사용하거나 사용할 새 변수를 만드는 대신 변수를 확인하고 설정하지 않은 경우 선호합니다.

예를 들어;

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

나는 실제로 이것에 대해 몇 달 전에 썼다. window.location.origin에 대한 픽스


주최자

var url = window.location.host;

보고 localhost:2679

호스트 이름

var url = window.location.hostname;

보고 localhost


window.location.origin 동일하게 충분합니다.


프로토콜 속성은 콜론 (:)을 포함하여 현재 URL의 프로토콜을 설정하거나 반환합니다.

즉, HTTP / HTTPS 부분 만 가져 오려면 다음과 같이 할 수 있습니다.

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

도메인의 경우 다음을 사용할 수 있습니다.

var domain = window.location.hostname;

포트의 경우 다음을 사용할 수 있습니다.

var port = window.location.port;

포트가 URL에 표시되지 않으면 빈 문자열이됩니다. 예를 들면 다음과 같습니다.

포트를 사용하지 않을 때 80/443을 표시해야하는 경우

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

실제로 window.location.origin 은 표준에 따라 브라우저에서 잘 작동하지만 추측합니다. IE는 표준을 따르지 않습니다.

따라서 IE, FireFox 및 Chrome에서 다음과 같이 작동했습니다.

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

그러나 충돌을 일으킬 수있는 향후 개선 가능성을 위해 "location"개체 앞에 "window"참조를 지정했습니다.

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

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

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

정규식 (Regex)을 사용해보십시오. 이는 유효성을 검사 / 추출하거나 자바 스크립트에서 간단한 구문 분석을 수행 할 때 매우 유용합니다.

정규식은 다음과 같습니다.

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

데모:

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]

이제 유효성 검사도 수행 할 수 있습니다.


사용중인 솔루션은 다음과 같습니다.

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

편집하다:

브라우저 간 호환성을 추가하려면 다음을 사용하십시오.

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

모든 브라우저에서 작동하는 간단한 답변 :

let origin;

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

origin = window.location.origin;

구성 가능한 매개 변수가있는 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
}

사용하지 않는 이유 :

let full = window.location.origin

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

참고 URL : https://stackoverflow.com/questions/6941533/get-protocol-domain-and-port-from-url