【问题标题】:slicing only the domain from the domain+TLD combination仅从域+TLD 组合中切片域
【发布时间】:2018-03-22 09:20:37
【问题描述】:

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

如果用户确实在其中之一,脚本会发出警报:

这个已经够了!

脚本的目的是提醒用户他停止访问这个网站(类似上瘾的行为)。

输出应仅包含域,不包含 TLD。

我尝试了以下失败的代码(代码在 tlds 集合上运行并使用该集合将它们剥离):

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! `);
    }
}

没有控制台错误。

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

【问题讨论】:

  • 试试let tlds = /\.(com|co\.il)/;let tlds = /\.(com|co\.il)$/;
  • 为什么投反对票?...我解释了我试图达到的目的、问题、尝试、错误上下文和重现。

标签: javascript regex regex-negation


【解决方案1】:

您应该迭代站点,如果 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
  }
}

【讨论】:

  • Shalom Ori。恳请您详细说明您在这里所做的与我所做的之间的区别。您说您“从头开始替换了所有内容”,但我想念您的意思。我看到您将正则表达式变量移到 if 内部并添加了一个具有特定域的新变量(为什么,我谦虚地希望它尽可能灵活)。
  • 我已经更新了代码,并添加了 cmets。现在清楚了吗?最终结果是您想要的吗?
  • 现在清楚多了,非常感谢!我还假设在 href 变量中,而不是 mako.co.il 我们可以放置一个正则表达式 [a-zA-Z]\..+ 以提供更“通用”的目的。
  • 关于脚本的用途 --- 学习如何仅打印站点的域对我来说很重要,因为它看起来更整洁。我尝试了几件失败的事情。该脚本只是帮助我处理我个人在某些网站上遇到的类似上瘾的行为。
  • href 变量替换了演示中的 window.location.href。在您的代码中,您应该使用window.location.href
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-05
  • 1970-01-01
  • 2010-11-07
  • 2010-10-16
相关资源
最近更新 更多