如何在 url 中将双/多斜杠替换为单斜杠

Jac*_*ack 6 javascript regex

我有一个这样的网址: http://127.0.0.1:7000//test//test//index.html

预期输出: http://127.0.0.1:7000/test/test/index.html

我使用这个正则表达式: [^http:](\/{2,})

输出是: http://127.0.0.1:700/test/test/index.html

匹配项是:'0//' '//'

这是演示:https : //www.debuggex.com/r/dXZouvlec4srhg8i

我错在哪里?

Wik*_*żew 7

您可以使用

var res = s.replace(/(https?:\/\/)|(\/)+/g, "$1$2"); // or
var res = s.replace(/(:\/\/)|(\/)+/g, "$1$2"); //  if you do not care of the : context
var res = s.replace(/(?<!:)\/\/+/g, "/"); // Same as 2) if your environment supports ECMAScript 2018
Run Code Online (Sandbox Code Playgroud)

请参阅此正则表达式演示此正则表达式演示,或另一个演示

详情

  • (https?:\/\/)- 将http://或捕获https://到组 1
  • | - 或者
  • (\/)+- 匹配一个或多个斜线,并且只有一个/保留在第 2 组中

在替换中,$1将 Group 1 内容插入回结果中(恢复协议),$2反向引用仅插入一个斜杠。

var res = s.replace(/(https?:\/\/)|(\/)+/g, "$1$2"); // or
var res = s.replace(/(:\/\/)|(\/)+/g, "$1$2"); //  if you do not care of the : context
var res = s.replace(/(?<!:)\/\/+/g, "/"); // Same as 2) if your environment supports ECMAScript 2018
Run Code Online (Sandbox Code Playgroud)


all*_*len 3

var str = 'http://127.0.0.1:7000//test//test//index.html';
str.replace(/([^:])(\/{2,})/g,"$1/");
Run Code Online (Sandbox Code Playgroud)

输出为“http://127.0.0.1:7000/test/test/index.html”。

模式 '[^http:]' 表示不匹配htp : ,所有这 4 个字符。