0

私は次のURLを持っており、これらのURLはすべてWebサイトのルートと見なされます。このパターンで「サイト」という単語が繰り返されていることに気付くと、正規表現を使用してjavascriptlocation.pathnameを使用して以下のパターンを決定するにはどうすればよいですか。

 http://www.somehost.tv/sitedev/
 http://www.somehost.tv/sitetest/
 http://www.somehost.tv/site/

 http://www.somehost.tv/sitedev/index.html
 http://www.somehost.tv/sitetest/index.html
 http://www.somehost.tv/site/index.html

ユーザーがWebサイトのルートにいる場合にのみ、jQueryダイアログを表示しようとしています。

4

3 に答える 3

2

DOMを使用してこれを解析するだけです。正規表現パーサーを呼び出す必要はありません。

var url = 'http://www.somesite.tv/foobar/host/site';
    urlLocation = document.createElement('a');

urlLocation.href = url;
alert(urlLocation.hostname);    // alerts 'www.somesite.tv'
于 2013-03-18T13:05:18.447 に答える
0

プロトコルとドメインを含む完全なパターンは、次のようになります。

/^http:\/\/www\.somehost\.tv\/site(test|dev)?\/(index\.html)?$/

しかし、あなたが対戦しているなら、location.pathname試してみてください

/^\/site(test|dev)?\/(index\.html)?$/.test(location.pathname)
于 2013-03-18T12:55:35.270 に答える
0

このために正規表現を明示的に必要としない場合

あなたはまた、例えばすることができます

  • 配列にURLを入力します
  • の減少する部分文字列をループします
    • 最短の要素。
  • との比較
    • 最長の要素。
  • それらが一致するまで。

 var urls = ["http://www.somehost.tv/sitedev/",
 "http://www.somehost.tv/sitetest/",
 "http://www.somehost.tv/site/",
 "http://www.somehost.tv/sitedev/index.html",
 "http://www.somehost.tv/sitetest/index.html",
 "http://www.somehost.tv/site/index.html"]

     function getRepeatedSub(arr) {
         var srt = arr.concat().sort();
         var a = srt[0];
         var b = srt.pop();
         var s = a.length;
         while (!~b.indexOf(a.substr(0, s))) {
             s--
         };
         return a.substr(0, s);
     }
 console.log(getRepeatedSub(urls)); //http://www.somehost.tv/site   

これがJSBinの例です

于 2013-03-18T14:06:27.930 に答える