檢查

2010-01-08 51 views
27

我用這個來檢查,如果有人從reddit的來到引薦,但它不工作。檢查

var ref = document.referrer; 
if(ref.match("/http://(www.)?reddit.com(/)?(.*)?/gi"){ 
    alert('You came from Reddit'); 
} else { 
    alert('No you didn\'t'); 
} 

有關正則表達式的建議也非常受歡迎。

回答

78

試試這個:

if (ref.match(/^https?:\/\/([^\/]+\.)?reddit\.com(\/|$)/i)) { 
    alert("Came from reddit"); 
} 

的正則表達式:

/^   # ensure start of string 
http  # match 'http' 
s?   # 's' if it exists is okay 
:\/\/  # match '://' 
([^\/]+\.)? # match any non '/' chars followed by a '.' (if they exist) 
reddit\.com # match 'reddit.com' 
(\/|$)  # match '/' or the end of the string 
/i   # match case-insenitive 
+15

+1對正則表達式的深入解釋。很有幫助。 – 2012-06-28 23:33:43

12

閉上你的if括號...

+0

Doh,它總是讓我看起來很愚蠢的東西。 – 2010-01-08 22:58:24

+3

:)每個人都會犯這樣的錯誤。使用會給你錯誤的東西(比如Firebug),因爲盯着一個默默無聞的JavaScript頁面是PITA。 – Skilldrick 2010-01-08 23:00:14

1

試試這個:

ref.match(new RegExp("^http://(www\\.)?reddit\\.com/", "i")) 

或者:

ref.match(/^http:\/\/(www\.)?reddit\.com\//i) 
-3

使用VAR REF = document.referer; //一個R,而不是兩個

+0

這與我所尋找的完全一致;標題中的引用者。 – cjbarth 2015-08-06 11:54:55

6

我一直在使用另一種由引薦尋找域

if (document.referrer.indexOf('reddit.com') >= 0) { alert('They came from Reddit.com'); } 

編輯於正則表達式:由於thekingoftruth指出,不若reddit的工作。 com包含在一個URL參數中,所以我將它擴展了一些。我還添加了toLowerCase(),因爲我發現在上面的RegExp中。

if (document.referrer.indexOf('?') > 0){ 
    if (document.referrer.substring(0,document.referrer.indexOf('?')).toLowerCase().indexOf('reddit.com') >= 0){ 
    alert('They came from Reddit'); 
    } 
} else { 
    if (document.referrer.toLowerCase().indexOf('reddit.com') > 0){ 
      alert('They came from Reddit'); 
    } 
} 
+2

唯一的問題是,如果引用者包含其中的子網址作爲查詢參數,說。 – thekingoftruth 2015-07-15 15:40:50

+1

公平點thekingoftruth。我想我可以檢查一下嗎?並在此之前觀察。我還添加了toLowerCase()。 我只是有點傷心(如果並不感到驚訝)表示,一條線解決方案是不再:-) – 2017-02-03 09:23:19

+0

我聽你的。 Javascript真的讓它很難擁有緊湊的單線程。 :( – thekingoftruth 2017-02-08 06:11:59