我需要在注册表单上确定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
}
会将https://www.example.co.uk/page1之类的所有网址都转换为example.com
和getDomainFromEmail
确实
export const getDomainFromEmail = (email) => {
return email.substring(email.lastIndexOf("@") + 1)
}
显然会将像myemail@example.com这样的电子邮件转换为example.com
问题是url域可能包含另一个子域,例如example.sub.com,其中上面的if
代码将返回false。电子邮件也可能包含一个子域。我不知道比较这些域的最可靠方法是什么
答案 0 :(得分:1)
您可以使用URL
对象从url和电子邮件中获取域,并使用regex删除子域。像这样:
const testData = [{
url: 'http://bar.com',
email: 'someone@bar.com'
}, {
url: 'http://foo.bar.com',
email: 'someone@bar.com'
}, {
url: 'http://bar.com',
email: 'someone@foo.bar.com'
}];
const getEmailDomain = (val) => {
return getDomain(`http://${val}`);
}
const getDomain = (val) => {
const host = new URL(val).host;
return host.match(/[^.]+\.[^.]+$/)[0];
};
console.log(testData.map(o => {
const urlDomain = getDomain(o.url);
const emailDomain = getEmailDomain(o.email);
const match = urlDomain === emailDomain;
return `url domain: ${urlDomain}, email domain: ${emailDomain} | match ${match}`;
}));
有两件事要记住,我正在从电子邮件地址创建URL(向它们添加http://
),在某些情况下可能会失败(电子邮件中包含无效的字符)网址),而我正在使用正则表达式提取可能也会失败的域名。
答案 1 :(得分:0)
首先,无需手动解析网址-这些天我们有了URL API。
所以:
let url = new URL(location);
let.host; //e.g. stackoverflow.com
这同样适用于子域,因为它们显然是主机的一部分。
您不能将电子邮件地址与URL()
一起使用,因此我们将通过删除所有内容(包括@符号在内)来手动进行操作。
let addr = 'foo@bar.bar2com';
let host = addr.replace(/^[^@]+@/, ''); //bar.bar2.com