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

使用正则表达式过滤URL域名前的协议但保留域名内的协议

解决方案

核心是只移除字符串开头的协议前缀(http://或https://),无论开头有多少个重复的协议,都不会影响URL内部的协议内容。

正则表达式与替换逻辑

使用锚定字符串起始位置的正则,匹配开头的一个或多个http:///https://,替换为空字符串:

const url = "http://http://www.somedomain.com/testing/ased=http://something";
const cleanedUrl = url.replace(/^(https?:\/\/)+/, '');
console.log(cleanedUrl); // 输出: www.somedomain.com/testing/ased=http://something

正则说明

  • ^:强制匹配字符串的起始位置,确保只处理开头的协议
  • https?:\/\/:匹配http://或https://(s?表示s可选,\/\/是对//的转义,避免与正则分界符冲突)
  • +:匹配前面的模式一次或多次,处理开头重复的协议前缀(比如http://http://这种情况)

不同场景测试验证

  • 场景1:带重复协议前缀的URL
    输入:http://http://www.somedomain.com/testing/ased=http://something
    输出:www.somedomain.com/testing/ased=http://something
  • 场景2:单协议前缀+非com后缀域名
    输入:https://example.org/path?redirect=http://test.com
    输出:example.org/path?redirect=http://test.com
  • 场景3:无前缀的URL(不会被修改)
    输入:www.test.net/abc=http://xyz
    输出:www.test.net/abc=http://xyz

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 22:41:05