Lo sto usando per verificare se qualcuno proviene da Reddit, tuttavia non funziona.
var ref = document.referrer; if(ref.match("/http://(www.)?reddit.com(/)?(.*)?/gi"){ alert('You came from Reddit'); } else { alert('No you didn\'t'); }
Anche i suggerimenti sull’espressione regolare sono i benvenuti.
Prova questo:
if (ref.match(/^https?:\/\/([^\/]+\.)?reddit\.com(\/|$)/i)) { alert("Came from reddit"); }
Il regexp:
/^ # 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
Chiudi il tuo if
paren …
Ho utilizzato un’alternativa a RegEx cercando il dominio nel referrer
if (document.referrer.indexOf('reddit.com') >= 0) { alert('They came from Reddit.com'); }
EDIT: come thekingoftruth sottolinea che non funziona se reddit.com è incluso in un parametro URL quindi l’ho esteso un po ‘. Ho anche aggiunto a LowerCase () come ho notato che nel RegExp sopra.
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'); } }
Prova questo:
ref.match(new RegExp("^http://(www\\.)?reddit\\.com/", "i"))
O:
ref.match(/^http:\/\/(www\.)?reddit\.com\//i)
Utilizzare var ref = document.referer; // ONE R invece di DUE