JSFiddle - React, Tailwind, and code Playground
JavaScript
let host_part_blacklist = ["www","login","accounts","edu","blog"];
let regex_regex = /[-\/\\^$*+?.()|[\]{}]/g;
function ci_search_regex(str) {
// case insensitive RegExp for use with String.search(...)
return new RegExp(str.replace(regex_regex, '\\$&'), 'i');
}
function hostMatchQuality(item, host) {
/* Match quality is ranked based on host parts contained in item.fullKey:
*
* 'cloud.bob.usr.example.com' > 'bob.usr.example.com' > 'usr.example.com' > 'example.com' \
* > 'cloud.bob.usr.example' > 'bob.usr.example' > 'usr.example' > 'example' \
* > 'cloud.bob.usr' > 'bob.usr' > 'usr'
* > 'bob.usr' > 'usr'
* > 'bob'
*
* The last part of the domain name (here: 'com') is considered to be a tld
* and *not* matched *alone*. Same applies to very short (less than 3 chars)
* and some very generic parts like "www"
*/
host = host.replace(/^\.+/, '').replace(/\.+$/, '');
let host_parts = host.split(/\.+/);
let tld = (host_parts.length >= 2) ? host_parts[host_parts.length-1] : "";
do {
// check a.b.c.d, then a.b.c, then a.b, ...
let quality = host.split(/\.+/).length*100 + host.split(/\.+/).length;
let subhost = host;
do {
// check a.b.c.d, then b.c.d, then c.d, ...
if (subhost.length < 3 || subhost == tld
|| host_part_blacklist.indexOf(subhost) >= 0) break;
let regex = ci_search_regex(subhost);
if (item.fullKey.search(regex) >= 0) return quality;
if (subhost.indexOf('.') < 0) break;
subhost = subhost.replace(/[^\.]+\.+/, '');
quality--;
} while (true);
if (host.indexOf('.') < 0) break;
host = host.replace(/\.+[^\.]+$/, '');
} while (true);
return -1;
}
document.body.textContent(hostMatchQuality({fullKey:"[email protected]@f.e.d.a"}, "c.b.a"));