我有一个这样的网址: 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
我错在哪里?
您可以使用
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)
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 个字符。
归档时间: |
|
查看次数: |
1711 次 |
最近记录: |