我有以下带正则表达式的 JS:
var ref = document.referrer;
if (ref.match(/^https?:\/\/([^\/]+\.)?sporedev\.ro\:\/index.html(\/|$)/i)) {
alert("Came from index");
}
我想要做的是,如果引用网址是网站的索引页或者引用网址不是网站的基本域,则不显示 HTML 的一部分。
我一直在研究这个正则表达式,修改我在 SO 上找到的一个正则表达式,以在域名后面添加 index.html。
这是初始脚本:
if (ref.match(/^https?:\/\/([^\/]+\.)?reddit\.com(\/|$)/i)) {
alert("Came from reddit");
}
如何在此正则表达式中正确添加“index.html”以及如何创建另一个条件来检查不同的基本 URL?
最佳答案
在这种情况下,请尝试采用最简单的方法。您可以使用 includes 而不是使用正则表达式。例如:
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
}
关于javascript - 检测引用源正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50066936/