JavaScript의 문자열에서 기본 URL을 추출하는 방법은 무엇입니까?


168

JavaScript (또는 jQuery)를 사용하여 문자열 변수에서 기본 URL을 추출하는 비교적 쉽고 안정적인 방법을 찾으려고합니다.

예를 들어, 다음과 같은 것이 주어집니다 :

http://www.sitename.com/article/2009/09/14/this-is-an-article/

나는 얻고 싶다 :

http://www.sitename.com/

정규식이 최선의 방법입니까? 그렇다면 주어진 문자열에서 추출한 기본 URL을 새 변수에 할당하기 위해 어떤 문장을 사용할 수 있습니까?

나는 이것에 대해 약간의 검색을했지만 JavaScript 세계에서 찾은 모든 것은 location.host 또는 유사한 것을 사용하여 실제 문서 URL 에서이 정보를 수집하는 것과 관련이있는 것 같습니다 .


요즘 대답은 다음과 같습니다
davidmpaz

답변:


205

편집 : 일부는 프로토콜을 고려하지 않는다고 불평합니다. 그래서 코드가 답변으로 표시되어 있기 때문에 코드를 업그레이드하기로 결정했습니다. 한 줄 코드를 좋아하는 사람들에게는 ... 우리가 왜 코드 최소화기를 사용하는지 유감스럽게 생각합니다. 코드는 사람이 읽을 수 있어야 하며이 방법은 더 좋습니다 ... 내 의견으로는.

var pathArray = "https://somedomain.com".split( '/' );
var protocol = pathArray[0];
var host = pathArray[2];
var url = protocol + '//' + host;

또는 아래에서 Davids 솔루션 을 사용하십시오 .


6
답장을 보내 주셔서 감사하지만 실제 문서 URL이 아닌 문자열에서 기본 URL을 추출하려고합니다. 나는 이것이 도움이 될 것이라고 생각하지 않습니다.하지만 내가 틀렸다면 정정하십시오.
Bungle

2
pathArray = String ( " YourHost.com/url/nic/or/not").split ( '/'); 호스트 = pathArray [2];

4
감사합니다-Rafal과 daddywoodland에게 감사합니다! 나는 다음을 사용하여 끝났다 : url = ' sitename.com/article/2009/09/14/this-is-an-article '; pathArray = (url) .split ( '/'); 호스트 = 'http : //'+ pathArray [2]; Rafal의 예제는 처리중인 모든 문자열에있는 "http : //"를 생략했다고 생각합니다.이 경우 pathArray [2]가 필요한 것입니다. "http : //"접두사가 없으면 pathArray [0]이됩니다. 다시 감사합니다.
Bungle

4
왜 모든 변수 선언입니까? url = 'sitename.com/article/2009/09/14/this-is-an-article'; newurl = 'http://' + url.split('/')[0];
ErikE

1
pathArray = window.location.href.split ( '/'); 프로토콜 = pathArray [0]; 호스트 = pathArray [2]; URL = 프로토콜 + ': //'+ 호스트; //now url === "http:://stackoverflow.com" 체크 아웃::

154

WebKit 기반 브라우저, 버전 21의 Firefox 및 최신 버전의 Internet Explorer (IE 10 및 11)가 구현 location.origin됩니다.

location.origin포함 프로토콜도메인 선택적와 포트 의 URL을.

예를 들어 location.originURL http://www.sitename.com/article/2009/09/14/this-is-an-article/http://www.sitename.com입니다.

지원하지 않고 브라우저를 대상으로하려면 location.origin다음과 같은 간결한 폴리 필 을 사용하십시오.

if (typeof location.origin === 'undefined')
    location.origin = location.protocol + '//' + location.host;

36
window.location.hostname주어진 경우 포트 번호가 누락되므로을 사용하십시오 window.location.host. 따라서 슬래시를 포함하여 완전한 '기본 이름'은 다음과 같습니다.window.location.protocol+"//"+window.location.host + "/";
sroebuck

4
실제로, 내 경우와 같이 다른 포트 번호를 제공해야하는 경우 window.location.hostname은 여전히 ​​유용합니다.
Darrell Brogdon

44

jQuery를 사용할 필요가 없습니다.

location.hostname

5
고마워-문자열로 사용할 수는 없습니까? 내 이해는 문서 URL에서만 작동한다는 것입니다.
Bungle

2
프로토콜 및 포트는 포함되지 않습니다.
David

32

링크 인 문자열에서 경로, 호스트 이름 등을 얻기 위해 분할을 수행 할 이유가 없습니다. 당신은 단지 링크를 사용해야합니다

//create a new element link with your link
var a = document.createElement("a");
a.href="http://www.sitename.com/article/2009/09/14/this-is-an-article/";

//hide it from view when it is added
a.style.display="none";

//add it
document.body.appendChild(a);

//read the links "features"
alert(a.protocol);
alert(a.hostname)
alert(a.pathname)
alert(a.port);
alert(a.hash);

//remove it
document.body.removeChild(a);

jQuery를 사용하여 요소를 추가하고 속성을 읽으면 쉽게 할 수 있습니다.


6
jQuery없이 몇 바이트로 수행하는 방법을 보여줄 때 왜 50K의 jQuery를 추가해야합니까?
Tim Down

13
포스터는 jQuery를 사용한다고 말합니다.
epascarello

1
아 그래, 충분히 공평 해 이것이 간단 할 때 jQuery를 사용하여 추가하는 추상화 계층을 사용하는 데 아무런 가치가 없습니다.
Tim Down

2
이 경우 전체 사이트가 jqUERY에서 실행된다고 가정하면 kquery는 실제로 단순화합니다.
trusktr

2
Ewww ... 이것이 최선의 방법은 아닙니다 ... window.location.href에서 추출하는 경우 window.location을 사용하십시오. 그렇지 않으면 정규식을 사용하십시오.
BMiner

21
var host = location.protocol + '//' + location.host + '/';

2
정답으로 간주되어야합니다.-프로토콜을 유지합니다
Katai

16
String.prototype.url = function() {
  const a = $('<a />').attr('href', this)[0];
  // or if you are not using jQuery 👇🏻
  // const a = document.createElement('a'); a.setAttribute('href', this);
  let origin = a.protocol + '//' + a.hostname;
  if (a.port.length > 0) {
    origin = `${origin}:${a.port}`;
  }
  const {host, hostname, pathname, port, protocol, search, hash} = a;
  return {origin, host, hostname, pathname, port, protocol, search, hash};

}

그런 다음 :

'http://mysite:5050/pke45#23'.url()
 //OUTPUT : {host: "mysite:5050", hostname: "mysite", pathname: "/pke45", port: "5050", protocol: "http:",hash:"#23",origin:"http://mysite:5050"}

요청하려면 다음이 필요합니다.

 'http://mysite:5050/pke45#23'.url().origin

Review 07-2017 : 더 우아하고 더 많은 기능이 있습니다.

const parseUrl = (string, prop) =>  {
  const a = document.createElement('a'); 
  a.setAttribute('href', string);
  const {host, hostname, pathname, port, protocol, search, hash} = a;
  const origin = `${protocol}//${hostname}${port.length ? `:${port}`:''}`;
  return prop ? eval(prop) : {origin, host, hostname, pathname, port, protocol, search, hash}
}

그때

parseUrl('http://mysite:5050/pke45#23')
// {origin: "http://mysite:5050", host: "mysite:5050", hostname: "mysite", pathname: "/pke45", port: "5050"…}


parseUrl('http://mysite:5050/pke45#23', 'origin')
// "http://mysite:5050"

멋있는!


12

jQuery를 사용하는 경우 이는 DOM에 요소를 추가하지 않고 자바 스크립트에서 요소를 조작하는 멋진 방법입니다.

var myAnchor = $("<a />");

//set href    
myAnchor.attr('href', 'http://example.com/path/to/myfile')

//your link's features
var hostname = myAnchor.attr('hostname'); // http://example.com
var pathname = myAnchor.attr('pathname'); // /path/to/my/file
//...etc

1
나는 그것이 있어야한다고 생각합니다 myAnchor.prop('hostname'). 지난 5 년 동안 jQuery가 바뀌었을 것 같습니다. 답변 주셔서 감사합니다!
Dehli

11

Douglas Crockford의 정규 표현식 규칙은 URL의 문자열 표현에서 기본 값을 얻는 간단한 방법입니다.

var yourUrl = "http://www.sitename.com/article/2009/09/14/this-is-an-article/";
var parse_url = /^(?:([A-Za-z]+):)?(\/{0,3})([0-9.\-A-Za-z]+)(?::(\d+))?(?:\/([^?#]*))?(?:\?([^#]*))?(?:#(.*))?$/;
var parts = parse_url.exec( yourUrl );
var result = parts[1]+':'+parts[2]+parts[3]+'/' ;

더 강력한 URL 조작 툴킷을 찾고 있다면 URI.js를 사용해보십시오. getter, setter, url normalization 등을 모두 멋진 체인 가능한 API로 지원합니다.

jQuery 플러그인을 찾고 있다면 jquery.url.js 가 도움이 될 것입니다.

@epascarello가 제안한 것처럼 앵커 요소를 사용하는 것이 더 간단한 방법입니다. 이것은 DOM 요소를 만들어야한다는 단점이 있습니다. 그러나 이것은 클로저에 캐시되어 여러 URL에 재사용 될 수 있습니다.

var parseUrl = (function () {
  var a = document.createElement('a');
  return function (url) {
    a.href = url;
    return {
      host: a.host,
      hostname: a.hostname,
      pathname: a.pathname,
      port: a.port,
      protocol: a.protocol,
      search: a.search,
      hash: a.hash
    };
  }
})();

다음과 같이 사용하십시오.

paserUrl('http://google.com');


8

window.location.href (주소 표시 줄)에서 정보를 추출하는 경우이 코드를 사용하여 다음을 가져옵니다 http://www.sitename.com/.

var loc = location;
var url = loc.protocol + "//" + loc.host + "/";

문자열, str즉 임의의 URL (window.location.href 아님)이있는 경우 정규식을 사용하십시오.

var url = str.match(/^(([a-z]+:)?(\/\/)?[^\/]+\/).*$/)[1];

나는 우주의 모든 사람들처럼 정규 표현식을 읽는 것을 싫어하므로 영어로 세분화합니다.

  • 0 개 이상의 알파 문자 다음에 콜론 (생략 할 수있는 프로토콜)이 있습니다.
  • //가 뒤 따릅니다 (생략 가능)
  • / (호스트 이름 및 포트)를 제외한 모든 문자가 뒤에옵니다.
  • /
  • 무엇이든 (경로, 적은 시작 /).

DOM 요소를 만들거나 미친 일을 할 필요가 없습니다.


7

URL에서 호스트를 추출하는 간단한 정규식을 사용합니다.

function get_host(url){
    return url.replace(/^((\w+:)?\/\/[^\/]+\/?).*$/,'$1');
}

이렇게 사용하세요

var url = 'http://www.sitename.com/article/2009/09/14/this-is-an-article/'
var host = get_host(url);

(가) 경우 참고 url로 끝날하지 않는 /hostA의 끝나지 않을 것입니다 /.

다음은 몇 가지 테스트입니다.

describe('get_host', function(){
    it('should return the host', function(){
        var url = 'http://www.sitename.com/article/2009/09/14/this-is-an-article/';
        assert.equal(get_host(url),'http://www.sitename.com/');
    });
    it('should not have a / if the url has no /', function(){
        var url = 'http://www.sitename.com';
        assert.equal(get_host(url),'http://www.sitename.com');
    });
    it('should deal with https', function(){
        var url = 'https://www.sitename.com/article/2009/09/14/this-is-an-article/';
        assert.equal(get_host(url),'https://www.sitename.com/');
    });
    it('should deal with no protocol urls', function(){
        var url = '//www.sitename.com/article/2009/09/14/this-is-an-article/';
        assert.equal(get_host(url),'//www.sitename.com/');
    });
    it('should deal with ports', function(){
        var url = 'http://www.sitename.com:8080/article/2009/09/14/this-is-an-article/';
        assert.equal(get_host(url),'http://www.sitename.com:8080/');
    });
    it('should deal with localhost', function(){
        var url = 'http://localhost/article/2009/09/14/this-is-an-article/';
        assert.equal(get_host(url),'http://localhost/');
    });
    it('should deal with numeric ip', function(){
        var url = 'http://192.168.18.1/article/2009/09/14/this-is-an-article/';
        assert.equal(get_host(url),'http://192.168.18.1/');
    });
});

6

현재 URL의 다른 매개 변수를 얻으려면 아래 코드를 사용할 수 있습니다

alert("document.URL : "+document.URL);
alert("document.location.href : "+document.location.href);
alert("document.location.origin : "+document.location.origin);
alert("document.location.hostname : "+document.location.hostname);
alert("document.location.host : "+document.location.host);
alert("document.location.pathname : "+document.location.pathname);

4
function getBaseURL() {
    var url = location.href;  // entire url including querystring - also: window.location.href;
    var baseURL = url.substring(0, url.indexOf('/', 14));


    if (baseURL.indexOf('http://localhost') != -1) {
        // Base Url for localhost
        var url = location.href;  // window.location.href;
        var pathname = location.pathname;  // window.location.pathname;
        var index1 = url.indexOf(pathname);
        var index2 = url.indexOf("/", index1 + 1);
        var baseLocalUrl = url.substr(0, index2);

        return baseLocalUrl + "/";
    }
    else {
        // Root Url for domain name
        return baseURL + "/";
    }

}

그런 다음 이처럼 사용할 수 있습니다 ...

var str = 'http://en.wikipedia.org/wiki/Knopf?q=1&t=2';
var url = str.toUrl();

url의 가치는 ...

{
"original":"http://en.wikipedia.org/wiki/Knopf?q=1&t=2",<br/>"protocol":"http:",
"domain":"wikipedia.org",<br/>"host":"en.wikipedia.org",<br/>"relativePath":"wiki"
}

"var url"에는 두 가지 방법이 있습니다.

var paramQ = url.getParameter('q');

이 경우 paramQ의 값은 1입니다.

var allParameters = url.getParameters();

allParameters의 값은 매개 변수 이름 일뿐입니다.

["q","t"]

IE, 크롬 및 파이어 폭스에서 테스트되었습니다.


1
뭔가 빠진 것 같습니다 ... toUrl은 어디에서 왔나요?
thomasf1 2016 년

3

window.location.protocol 및 window.location.origin을 설명하지 않고 지정된 포트 번호가 누락되는 등 모든 것을 세 번째 "/"까지 가져옵니다.

// get nth occurrence of a character c in the calling string
String.prototype.nthIndex = function (n, c) {
    var index = -1;
    while (n-- > 0) {
        index++;
        if (this.substring(index) == "") return -1; // don't run off the end
        index += this.substring(index).indexOf(c);
    }
    return index;
}

// get the base URL of the current page by taking everything up to the third "/" in the URL
function getBaseURL() {
    return document.URL.substring(0, document.URL.nthIndex(3,"/") + 1);
}


1

정규식을 사용하여 수행 할 수 있습니다.

/(http:\/\/)?(www)[^\/]+\//i

맞습니까?


1
흠, 제한된 정규식 기술로 볼 때, 그것은 적어도 가깝습니다. 최고의 정규 표현식을 좁히는 데 도움이되는지 확인하기 위해 질문에 더 많은 정보를 추가 할 것입니다.
Bungle

1
나는 그것이 더 쉬운 해결책이기 때문에 문자열에 .split ( '/')을 사용하게되었습니다. 그래도 도움을 주셔서 감사합니다!
Bungle

2
https URL? www로 시작하지 않는 호스트 이름? 어쨌든 www를 캡처해야합니까?
Tim Down

1
모르겠다. OP는 URL을 잡는 방법을 물었고 그의 예에는 http & www가있었습니다.
Clement Herreman

1

웹 사이트 ( /my/path) 또는 스키마리스 ( //example.com/my/path) 또는 전체 ( http://example.com/my/path) 내의 경로를 포함하여 URL의 출처를 얻으려면 빠른 기능을 모았습니다.

아래 스 니펫에서 세 통화 모두가 로그에 기록되어야합니다 https://stacksnippets.net.

function getOrigin(url)
{
  if(/^\/\//.test(url))
  { // no scheme, use current scheme, extract domain
    url = window.location.protocol + url;
  }
  else if(/^\//.test(url))
  { // just path, use whole origin
    url = window.location.origin + url;
  }
  return url.match(/^([^/]+\/\/[^/]+)/)[0];
}

console.log(getOrigin('https://stacksnippets.net/my/path'));
console.log(getOrigin('//stacksnippets.net/my/path'));
console.log(getOrigin('/my/path'));


0

이것은 나를 위해 작동합니다 :

var getBaseUrl = function (url) {
  if (url) {
    var parts = url.split('://');
    
    if (parts.length > 1) {
      return parts[0] + '://' + parts[1].split('/')[0] + '/';
    } else {
      return parts[0].split('/')[0] + '/';
    }
  }
};


0
var tilllastbackslashregex = new RegExp(/^.*\//);
baseUrl = tilllastbackslashregex.exec(window.location.href);

window.location.href는 브라우저 주소 표시 줄에서 현재 URL 주소를 제공합니다

이 같은 모든 일이 될 수 있습니다 https://stackoverflow.com/abc/xyz 또는 https://www.google.com/search?q=abc tilllastbackslashregex.exec () 실행 정규식과 마지막 백 슬래시까지 일치하는 문자열 즉 retun HTTPS를 : //stackoverflow.com/abc/ 또는 https://www.google.com/ 각각


5
간단한 설명을 추가하십시오.
Preet

6
검토 대기열에서 : 소스 코드 주위에 컨텍스트를 추가하도록 요청하십시오. 코드 전용 답변은 이해하기 어렵습니다. 게시물에 더 많은 정보를 추가 할 수 있다면 asker와 향후 독자 모두에게 도움이 될 것입니다.
RBT

0

좋은 방법은 JavaScript 네이티브 API URL객체 를 사용하는 것 입니다. 이것은 많은 유용한 URL 부분을 제공합니다.

예를 들면 다음과 같습니다.

const url = '/programming/1420881/how-to-extract-base-url-from-a-string-in-javascript'

const urlObject = new URL(url);

console.log(urlObject);


// RESULT: 
//________________________________
hash: "",
host: "stackoverflow.com",
hostname: "stackoverflow.com",
href: "/programming/1420881/how-to-extract-base-url-from-a-string-in-javascript",
origin: "https://stackoverflow.com",
password: "",
pathname: "/questions/1420881/how-to-extract-base-url-from-a-string-in-javaript",
port: "",
protocol: "https:",
search: "",
searchParams: [object URLSearchParams]
... + some other methods

여기서 볼 수 있듯이 필요한 모든 것에 액세스 할 수 있습니다.

예를 들면 다음과 같습니다. console.log(urlObject.host); // "stackoverflow.com"

URL을 위한 문서

당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.