web-dev-qa-db-ja.com

URLからプロトコル、ドメイン、およびポートを取得する

与えられたURLから完全なプロトコル、ドメイン、そしてポートを抽出する必要があります。例えば:

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

まず現在の住所を取得する

var url = window.location.href

それからその文字列を解析するだけです。

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

あなたのURLは:

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

お役に立てれば

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

これらの答えのどれもが、現在のページのURLではなく、任意のURLを要求する質問に完全に対処しているようには見えません。

方法1:URL APIを使用する(警告:IE11はサポートされていません)

あなたは RL API を使うことができます(IE11ではサポートされていませんが、利用可能な 他のどこでも )。

これにより、 search params に簡単にアクセスできます。もう1つの利点は、DOMに依存しないため、Webワーカーで使用できることです。

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('searchIndex');  // '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' }
157
David Calhoun

どういうわけかすべての答えはすべてやり過ぎです。これだけです。

window.location.Origin

詳細については、こちらをご覧ください。 https://developer.mozilla.org/en-US/docs/Web/API/window.location#Properties

118
Pijusn

すでに言及したように、まだ完全にはサポートされていない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 の修正

50
Toby

ホスト

var url = window.location.Host;

localhost:2679を返します

ホスト名

var url = window.location.hostname;

localhostを返します

30
Miroslav Holec

Protocolプロパティは、コロン(:)を含め、現在の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は同じ結果を得るのに十分でしょう。

12
int soumen

確かに、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: '');
6
cpu
var getBasePath = function(url) {
    var r = ('' + url).match(/^(https?:)?\/\/[^/]+/i);
    return r ? r[0] : '';
};
2
haipeng

正規表現(Regex)を使ってみてください。これは、ものを検証/抽出したいときや、JavaScriptで簡単な構文解析をしたいときにも非常に役立ちます。

正規表現は次のとおりです。

/([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]

これで検証もできます。

2
ed9w2in6
var http = location.protocol;
var slashes = http.concat("//");
var Host = slashes.concat(window.location.hostname);
2
Elankeeran

これが私が使っている解決策です:

const result = `${ window.location.protocol }//${ window.location.Host }`;
0
JulienRioux

すべてのブラウザに有効な簡単な答え:

let Origin;

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

Origin = window.location.Origin;
0
Mike Hawes

使用しない理由:

let full = window.location.Origin
0
Maik de Kruif

設定可能なパラメータを持つ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
}
0
Sébastien

window.location.protocol + '//' + window.location.Host

0
Code_Worm