Javascript 如何确定url域是否与电子邮件域匹配

Javascript 如何确定url域是否与电子邮件域匹配,javascript,reactjs,Javascript,Reactjs,我需要找出url域是否与我的注册表上的电子邮件域匹配。通过比较url和电子邮件域中的域,我已经做到了这一点 if (getDomainFromUrl(url) === getDomainFromEmail(email)) { console.log("Match") } else { console.log("Doesn't match") } 其中getDomainFromUrl执行 export const getDomainFromUrl = (url)

我需要找出url域是否与我的注册表上的电子邮件域匹配。通过比较url和电子邮件域中的域,我已经做到了这一点

if (getDomainFromUrl(url) === getDomainFromEmail(email)) {
      console.log("Match")
  } else {
      console.log("Doesn't match")
  }
其中
getDomainFromUrl
执行

export const getDomainFromUrl = (url) => {
    let hostname = "";

    if (url.indexOf("//") > -1) {
        hostname = url.split('/')[2];
    }
    else {
        hostname = url.split('/')[0];
    }

    hostname = hostname.split(':')[0];
    hostname = hostname.split('?')[0];
    if(hostname.split('www.')[1]) {
        hostname = hostname.split('www.')[1]
    }

    return hostname
}
export const getDomainFromEmail = (email) => {
    return email.substring(email.lastIndexOf("@") + 1)
}
这会将任何类似example.com的url转换为example.com

而且
getDomainFromEmail
确实如此

export const getDomainFromUrl = (url) => {
    let hostname = "";

    if (url.indexOf("//") > -1) {
        hostname = url.split('/')[2];
    }
    else {
        hostname = url.split('/')[0];
    }

    hostname = hostname.split(':')[0];
    hostname = hostname.split('?')[0];
    if(hostname.split('www.')[1]) {
        hostname = hostname.split('www.')[1]
    }

    return hostname
}
export const getDomainFromEmail = (email) => {
    return email.substring(email.lastIndexOf("@") + 1)
}
这显然会使电子邮件变得像myemail@example.com进入example.com


问题是url域可能包含另一个子域,例如.sub.com,其中上面的
if
code将返回false。此外,电子邮件可能包含子域。我不知道比较这些域最可靠的方法是什么

首先,不需要手动解析URL,现在我们有了最可靠的方法

因此:

这也适用于子域,因为它们显然是主机的一部分

您不能将电子邮件地址与
URL()
一起使用,因此我们将手动删除@符号之前的所有内容

let addr = 'foo@bar.bar2com';
let host = addr.replace(/^[^@]+@/, ''); //bar.bar2.com

您可以使用
URL
对象从URL和电子邮件获取域,并使用regex删除子域。大概是这样的:

const testData=[{
网址:'http://bar.com',
电邮:'someone@bar.com'
}, {
网址:'http://foo.bar.com',
电邮:'someone@bar.com'
}, {
网址:'http://bar.com',
电邮:'someone@foo.bar.com'
}];
常量getEmailDomain=(val)=>{
返回getDomain(`http://${val}`);
}
常量getDomain=(val)=>{
const host=新URL(val).host;
返回host.match(/[^.]+\.[^.]+$/)[0];
};
log(testData.map(o=>{
const urlDomain=getDomain(o.url);
const emailDomain=getEmailDomain(o.email);
const match=urlDomain==emailDomain;
返回'url域:${urlDomain},电子邮件域:${emailDomain}| match${match}`;

}));您可以尝试URI库。这有一个方便的方法“domain”,可以为您提取域。我想OP需要
someone@bar.com
http://foo.bar.com
(忽略子域)。谢谢Titus。。。我将尝试在我的代码中实现这一点,如果可行,我会将您的这一点标记为Answered小心地“删除子域”…
foo@baz.example.com
可能或多或少被认为是“属于”example.com
。将相同的逻辑应用于
foo@baz.co.uk
然而这可能相当危险。@04FS是的,我忘记了两级国家代码。