簡體   English   中英

使用子域檢測 url 中的主機

[英]Detect host of in a url with a subdomain

如果有一堆 URL:

  • sub1.sub.example.com

  • sub2.sub.example.com

  • sub3.sub.example.com

  • sub4.sub.example.com

  • 等等。

如何檢測主機名是否為something.sub.example.com

我試過的,這不起作用:

if (window.location.hostname == "*.sub.example.com") {
  //actions 
}

我相信你可以使用String#endsWith來做你想做的事:

if (window.location.hostname.endswith(".sub.example.com")) { . . . }

正如 Jake Holzinger 在評論中指出的那樣,IE 不支持String#endsWith 一個具有更好兼容性的簡單正則表達式解決方案將

// This is a Regular Expression literal meaning
// a string ending with ".sub.example.com" (case-insensitive)
var regexSubdomainPattern = /\.sub\.example\.com$/ig;
if (regexSubdomainPattern.test(window.location.hostname)) { . . . }

String (object) Prototype包含一個方便的方法,稱為includes()

因此,您可以采用任何字符串參數並使用以下代碼

 function ddcc(what){ // ddcc - domain dot com check return what.includes('sub.example.com'); } var test = 'wwww.madeup.sub.example.com'; console.log(ddcc(test)); // so in practice - if ddcc(window.location.hostname) { .. } will do the trick

應該很好地為您服務。


編輯:如果您堅持.hostname結尾sub.example.com ,沒有別的,那么:

 function ddcc(what) { // ddcc - domain dot com check return what.includes('sub.example.com') ? what.substring(what.indexOf('sub.example.com'), what.length) === 'sub.example.com' : false; } var test = 'madeup.sub.example.com.fakelink'; console.log(ddcc(test));

如您所見,我將.fakelink附加到我們的test變量中。 盡管它包含sub.example.com但它仍然返回false

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM