如何使用JavaScript编写判断指定子域名是否匹配的函数?
你现在的代码有两个比较明显的问题:
- 逻辑是硬编码固定匹配
news.google.com这一个域名,完全不具备通用的子域名判断能力 - 参数
t没有明确定义用途,你当前调用时传入的x是未赋值的变量,不匹配目标域名时函数会直接返回undefined,没法得到明确的布尔判断结果
如果你需要的是通用判断当前域名是否为指定主域名的子域名(包含主域名本身),可以参考下面的实现:
/** * 判断当前hostname是否属于指定主域名的子域名/主域名本身 * @param {string} mainDomain 待匹配的主域名,例如 'google.com' * @returns {boolean} 匹配结果 */ function isSubdomainOf(mainDomain) { const hostname = window.location.hostname; // 完全匹配主域名的情况直接返回true if (hostname === mainDomain) return true; // 子域名的结尾一定是 .主域名,例如news.google.com结尾是.google.com return hostname.endsWith(`.${mainDomain}`); } // 调用示例:判断是否是google.com的子域名 console.log(isSubdomainOf('google.com')); // news.google.com会返回true,baidu.com会返回false
如果你只是需要匹配固定的几个子域名,比如仅匹配news.google.com、maps.google.com,可以用数组包含的方式实现:
function isAllowedSubdomain() { const allowedList = ['news.google.com', 'maps.google.com']; return allowedList.includes(window.location.hostname); } console.log(isAllowedSubdomain());
如果你的需求还有其他特殊规则,可以基于上面的逻辑调整判断条件即可。
内容的提问来源于stack exchange,提问作者mpberg
相关产品推荐
相关产品推荐

