仅从域+TLD 组合中切分域

slicing only the domain from the domain+TLD combination

我尝试编写一个 Greasemonkey 用户脚本来检查用户是否在网站列表之一中。

如果用户确实在其中之一,脚本会提示:

Enough with this domain already!

该脚本的目的是提醒用户停止访问该站点(类似成瘾行为)。

输出应该只包含域,没有 TLD。

我尝试了以下失败的代码(该代码在一组顶级域名上运行并使用该集合将其剥离):

let sites = ['walla.com', 'mako.co.il'];
let tlds = new RegExp('\.+(com|co.il)');

for (let i = 0; i < sites.length; i++) {
    if (window.location.href.indexOf(sites[i]) != -1 ) {
        sites.forEach((e)=>{
            e.replace(tlds, '').split('.').pop(),
        });

     alert(` Enough with this ${sites[i]} already! `);
    }
}

没有控制台错误。

要重现,请在 Greasemoneky/Tampermonkey 中安装脚本并在列出的站点中尝试。

您应该迭代站点,如果 href 包含该站点 (sites[i]),请替换域之后的所有内容(从 don 开始),发出警报并打破循环:

const sites = ['walla.com', 'mako.co.il'];
const regex = /\..+/;
const href = 'http://www.mako.co.il/news?partner=NavBar'; // this replace window.location.href for demo purposes

for (let i = 0; i < sites.length; i++) {
  if (href.includes(sites[i])) { // if the href includes the sites[i]
    const domain = sites[i].replace(regex, ''); // remove the 1st dot and everything after it to get the domain name

    alert(` Enough with this ${domain} already! `);
    
    break; // or return if in a function
  }
}