我用它来检查是否有人来自Reddit,但是它不起作用.
var ref = document.referrer; if(ref.match("/http://(www.)?reddit.com(/)?(.*)?/gi"){ alert('You came from Reddit'); } else { alert('No you didn\'t'); }
关于正则表达的建议也是最受欢迎的.
试试这个:
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
关闭你的if
paren ......
通过在引荐来源中查找域名,我一直在使用RegEx的替代方案
if (document.referrer.indexOf('reddit.com') >= 0) { alert('They came from Reddit.com'); }
编辑:正如thekingoftruth指出,如果reddit.com包含在URL参数中不起作用,所以我已经扩展了一点.当我在上面的RegExp中发现时,我也添加了toLowerCase().
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'); } }