Javascript 检测引用源正则表达式

Javascript 检测引用源正则表达式,javascript,regex,Javascript,Regex,我有以下带有正则表达式的JS: var ref = document.referrer; if (ref.match(/^https?:\/\/([^\/]+\.)?sporedev\.ro\:\/index.html(\/|$)/i)) { alert("Came from index"); } 我想做的是,如果推荐人是网站的索引页,或者如果推荐人不是网站的基本域,则不显示HTML的一部分 我一直在处理这个正则表达式,修改我在上找到的一个,以便在域名后添加index.htm

我有以下带有正则表达式的JS:

var ref = document.referrer;
if (ref.match(/^https?:\/\/([^\/]+\.)?sporedev\.ro\:\/index.html(\/|$)/i)) {
  alert("Came from index");
}       
我想做的是,如果推荐人是网站的索引页,或者如果推荐人不是网站的基本域,则不显示HTML的一部分

我一直在处理这个正则表达式,修改我在上找到的一个,以便在域名后添加index.html

这是初始脚本:

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

如何在这个正则表达式中正确添加index.html,以及如何创建另一个条件来检查不同的基本URL?

在这种情况下,请尝试采用最简单的方法。您可以使用正则表达式代替正则表达式。例如:

if (ref.includes('index.html') {
  //do something
}

如果你真的想使用正则表达式,那么就考虑一些简单的事情:

if (/index\.html/.test(ref)) {
  //do something
}
关于域的匹配,我认为将域列表放在一个数组中可能是一个很好的方法,这样您就可以执行以下操作:

const domains = ['https://foo.com', 'https://bar.com'];

if (domains.indexOf(ref) > -1) {
  //do something
}
const domains = ['https://foo.com', 'https://bar.com'];
const fromIndex = ref.includes('index.html');
const fromDomainList = domains.indexOf(ref) > -1;

if (fromIndex || fromDomainList) {
  //do something
}
然后,您可以将这些方法与以下内容相结合:

const domains = ['https://foo.com', 'https://bar.com'];

if (domains.indexOf(ref) > -1) {
  //do something
}
const domains = ['https://foo.com', 'https://bar.com'];
const fromIndex = ref.includes('index.html');
const fromDomainList = domains.indexOf(ref) > -1;

if (fromIndex || fromDomainList) {
  //do something
}
常量域=['https://foo.com', 'https://bar.com']; const fromIndex=ref.includes'index.html';const fromDomainList=domains.indexOfref>-1;如果fromIndex | | fromDomainList{Alerts来自home、foo.com或bar.com;}或者{Alerts来自其他页面;}我试图这样解决它,但它似乎没有显示任何警报。你知道为什么吗?