You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Google Scripts URL解析API替代方案及子域名比对需求咨询

解决方案

优先使用内置URL接口(无需外部调用/正则)

Google Apps Script 目前V8运行时已原生支持标准Web URL 接口,不需要依赖正则表达式,也无需调用第三方托管服务,天然支持国际URL解析,完全适配你的业务需求。
你可以基于URL接口重写scoreURL函数,代码如下:

function scoreURL(urlOne, urlTwo) {
  try {
    // 解析两个URL,自动处理协议、国际域名、端口、编码等特殊场景
    const u1 = new URL(urlOne);
    const u2 = new URL(urlTwo);
    
    // 统一移除前缀www,域名不区分大小写
    const domain1 = u1.hostname.replace(/^www\./i, '').toLowerCase();
    const domain2 = u2.hostname.replace(/^www\./i, '').toLowerCase();
    
    // 如需支持子域名归属判断(比如a.example.com属于example.com的子域名),可替换下方域名对比逻辑
    if (domain1 !== domain2) return -1;
    
    // 路径+参数+锚点完全相等(包含空路径即首页)返回1,同域名不同路径返回0
    const fullPath1 = u1.pathname + u1.search + u1.hash;
    const fullPath2 = u2.pathname + u2.search + u2.hash;
    return fullPath1 === fullPath2 ? 1 : 0;
  } catch (e) {
    // 可根据业务需求调整非法URL的处理逻辑
    throw new Error('输入URL格式不合法:' + e.message);
  }
}

子域名判断补充逻辑

如果需要支持子域名归属校验,可将上述代码中domain1 !== domain2的判断替换为以下逻辑:

// 倒序拆分域名段,比如a.example.com拆分为['com','example','a']
const parts1 = domain1.split('.').reverse();
const parts2 = domain2.split('.').reverse();
// 匹配顶级+二级域名共2段,相同即认为是同根域名下的子域名
const matchLevel = Math.min(2, parts1.length, parts2.length);
let isSameRoot = true;
for (let i = 0; i < matchLevel; i++) {
  if (parts1[i] !== parts2[i]) {
    isSameRoot = false;
    break;
  }
}
if (!isSameRoot) return -1;

如果你的脚本当前使用旧版Rhino运行时,仅需要在脚本设置中切换为V8运行时即可使用上述接口,无需额外配置。

内容的提问来源于stack exchange,提问作者ThePirate

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 11:06:03