Reputation: 608
I have the following JS with regex:
var ref = document.referrer;
if (ref.match(/^https?:\/\/([^\/]+\.)?sporedev\.ro\:\/index.html(\/|$)/i)) {
alert("Came from index");
}
What I'm trying to do, is to not display a part of HTML if the referrer is the index page of the website or if the referrer is other than the base domain of the website.
I've been working on this regex, modifying one that I found on SO to add the index.html after the domain name.
This is the initial script:
if (ref.match(/^https?:\/\/([^\/]+\.)?reddit\.com(\/|$)/i)) {
alert("Came from reddit");
}
How can I correctly add "index.html" in this regex and how can I create another condition to check for different base URL?
Upvotes: 0
Views: 124
Reputation: 21
In situations like these, try to adopt the simplest approach. Instead of using regex you could use includes. For example:
if (ref.includes('index.html') {
//do something
}
If you really want to use regex then consider something simple like:
if (/index\.html/.test(ref)) {
//do something
}
Regarding the matching of domains, I think it may be a good approach to put your list of domains in an array so you can do something like:
const domains = ['https://foo.com', 'https://bar.com'];
if (domains.indexOf(ref) > -1) {
//do something
}
You could then combine these approaches with something like:
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
}
Upvotes: 1