javascript 用于匹配 URL 中多个正斜杠的正则表达式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15638104/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Regex for matching multiple forward slashes in URL
提问by geochr
I need a regular expression for replacing multiple forward slashes in a URL with a single forward slash, excluding the ones following the colon
我需要一个正则表达式来用单个正斜杠替换 URL 中的多个正斜杠,不包括冒号后面的那些
e.g. http://link.com//whatever///
would become http://link.com/whatever/
例如http://link.com//whatever///
会变成http://link.com/whatever/
采纳答案by geochr
As you already accepted an answer. To show some more extend of matching and controlling the matches, this might help you in the future:
因为您已经接受了答案。为了显示匹配和控制匹配的更多扩展,这可能会在将来对您有所帮助:
var url = 'http://link.com//whatever///';
var set = url.match(/([^:]\/{2,3})/g); // Match (NOT ":") followed by (2 OR 3 "/")
for (var str in set) {
// Modify the data you have
var replace_with = set[str].substr(0, 1) + '/';
// Replace the match
url = url.replace(set[str], replace_with);
}
console.log(url);
Will output:
将输出:
http://link.com/whatever/
Doublets won't matter in your situation. If you have this string:
双峰在你的情况下无关紧要。如果你有这个字符串:
var url = 'http://link.com//om/om/om/om/om///';
Your set
array will contain multiple m//
. A bit redundant, as the loop will see that variable a few times. The nice thing is that String.replace()
replaces nothing if it finds nothing, so no harm done.
您的set
数组将包含多个m//
. 有点多余,因为循环会多次看到该变量。好消息是,String.replace()
如果它什么也没找到,它就什么都不替换,所以不会造成任何伤害。
What you could do is strip out the duplicates from set
first, but that would almost require the same amount of resources as just letting the for-loop go over them.
您可以做的是从set
一开始就去除重复项,但这几乎需要与让 for 循环遍历它们相同数量的资源。
Good luck!
祝你好运!
回答by Halcyon
I think this should work: /[^:](\/+)/
or /[^:](\/\/+)/
if you want only multiples.
我认为这应该有效:/[^:](\/+)/
或者/[^:](\/\/+)/
如果你只想要multiples。
It wont match leading //
but it looks like you're not looking for that.
它不会匹配领先,//
但看起来你不是在寻找那个。
To replace:
取代:
"http://test//a/b//d".replace(/([^:]\/)\/+/g, "") // --> http://test/a/b/d
回答by Ahmed KRAIEM
result = subject.replace(/(?<!http:)\/*\//g, "/");
or (for http, https, ftp and ftps)
或(对于 http、https、ftp 和 ftps)
result = subject.replace(/(?<!(?:ht|f)tps?:)\/*\//g, "/");