欢迎光临
我们一直在努力

html标记网站主域名

什么是网站主域名?

网站主域名是指完整域名中的核心部分,通常由二级域名和顶级域名组成。

步骤 代码示例 说明 获取完整URL const url = window.location.href; https://sub.example.com/path 创建URL对象 const urlObj = new URL(url); 解析URL为结构化对象 提取主域名 const mainDomain = urlObj.hostname.replace(/^www./, ''); 移除www.前缀,保留主域名

方法2:使用正则表达式匹配主域名

通过正则表达式直接提取主域名部分。

正则表达式 适用场景 示例 ^(?:https?://)?(?:www.)?([^/]+) 匹配带协议或www.的URL https://sub.example.com/pathexample.com ^([^.]+.[^.]+)$ 直接匹配主域名(无子域名) example.comexample.com

方法3:借助第三方库(如domain-parser

使用轻量级库自动解析主域名,支持复杂场景(如多级子域名)。

// 引入库
const domainParser = require('domain-parser');
// 解析主域名
const result = domainParser('https://sub.example.co.uk');
console.log(result.domain); // 输出:example.co.uk

常见问题与解答

问题1:如何区分主域名和子域名?

解答
主域名是域名的核心部分(如example.com),而子域名是主域名前的前缀(如sub.example.com中的sub),通过正则表达式或URL对象提取时,需移除www.等子域名前缀。


const url = 'https://example.com:8080/path';
const mainDomain = new URL(url).hostname; // 结果:example.com

未经允许不得转载:九八云安全 » html标记网站主域名