提取子域名和顶级域名需要更精细的字符串操作。我们可以使用split()
方法,对域名字符串按照点(.
)进行分割,然后根据需求获取相应的部分:
let host = "subdomain.example.com";
let parts = host.split('.');
let topLevelDomain = parts.slice(-2).join('.');
let subdomain = parts.slice(0, -2).join('.');
在这里,topLevelDomain
存储的将是如example.com
的顶级域名,而subdomain
则是如subdomain
的子域名。
const host = originalUrl?.split("/")[2] || ""; // 获取域名地址
const original = host.split(".").slice(0, -2).join("."); //获取子域名