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

JavaScript中将主机名/域名转换为有效URL的优雅方案

优雅且健壮的域名转HTTP URL实现方案

你的现有实现已经能处理大部分常规场景,但存在几个可以优化的点:比如未处理空输入、非法域名、忽略协议大小写,也没对非HTTP/HTTPS协议的情况做处理。下面是更健壮的实现方案:

改进后的代码实现

const domainToURL = (domain: string, defaultProtocol: string = 'https'): string => {
  // 校验输入合法性
  if (typeof domain !== 'string' || domain.trim() === '') {
    throw new Error('域名输入不能为空或非字符串');
  }
  const trimmedDomain = domain.trim();
  
  // 检查是否已包含HTTP/HTTPS协议(忽略大小写)
  const hasValidProtocol = /^https?:\/\//i.test(trimmedDomain);
  const urlStr = hasValidProtocol ? trimmedDomain : `${defaultProtocol}://${trimmedDomain}`;
  
  try {
    // 用原生URL对象解析,确保格式合规
    const url = new URL(urlStr);
    // 返回协议+主机的完整基础URL(包含端口)
    return `${url.protocol}//${url.host}`;
  } catch (err) {
    throw new Error(`无效域名格式: ${domain}`);
  }
};

实现优势

  • 输入校验:提前拦截空值、非字符串输入,避免后续解析报错
  • 协议兼容:识别大小写不敏感的HTTP/HTTPS协议(比如HTTP://example.com也能正确保留原协议)
  • 错误处理:捕获URL解析异常,对example..com这类非法域名抛出明确错误
  • 灵活配置:支持自定义默认协议,可根据需求切换为http
  • 端口处理:自动保留域名中的端口信息(比如example.com:3000会转为https://example.com:3000)

测试示例

  • domainToURL('example.com') → 返回 https://example.com
  • domainToURL('HTTP://example.com') → 返回 http://example.com
  • domainToURL('example.com:8080') → 返回 https://example.com:8080
  • domainToURL('invalid..domain') → 抛出错误 无效域名格式: invalid..domain

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 03:55:28