URL を解析してホスト名を取得する方法を探している投稿がたくさんあります。通常の解決策は、ドキュメント要素を作成し、URL を設定して、.hostname プロパティにアクセスすることです。それは素晴らしい解決策です。私はこのテクニックを少し超えるのに苦労しています。
ホスト名からベースホストを正常に抽出する機能があります。ベースホストの意味を説明するために (正しい命名法がわからない)、関数を示し、いくつかの入力出力の例を示します。
function parseURL(url) {
var parser = document.createElement('a');
parser.href = url;
url = parser.hostname;
//get a version of the url with the last "." and everything beyond it truncated.
//Uses this as a trick in the next step to get the "second to last" index.
url = url.substr(0, url.lastIndexOf("."));
//get a version of the url with everything before the second to last "." truncated.
url = parser.hostname.substr(url.lastIndexOf(".")+1);
return url;
};
parseURL("http://code.google.com/p/jsuri/")
//google.com - I don't think jsuri handle hosts any more effectively
parseURL("http://www.nytimes.com/pages/nyregion/index.html")
//nytimes.com
parseURL("http://fivethirtyeight.blogs.nytimes.com/2013/01/12/in-cooperstown-a-crowded-waiting-room/"
//nytimes.com
parseURL("http://www.guardian.co.uk/uk/2013/jan/13/fears-lulworth-cove-development-heritage"
//co.uk
最後の例は、私が恐れている例外であり、より実行可能な解決策を探している理由です。ホストを取得するための .hostname メソッドは、優れた最初のステップです。基本レベルのホストの前にあるサブホストをハッキングするためのより良い方法を探しています。
助けていただければ幸いです(私の用語を修正するだけであれば)。