用于匹配URL中的多个正斜杠的正则表达式 [英] Regex for matching multiple forward slashes in URL
问题描述
我需要一个正则表达式来替换带有单个正斜杠的URL中的多个正斜杠,不包括冒号
I need a regular expression for replacing multiple forward slashes in a URL with a single forward slash, excluding the ones following the colon
之后的正斜杠。 http://link.com//whatever///
将成为 http://link.com/whatever/
e.g. http://link.com//whatever///
would become http://link.com/whatever/
推荐答案
您已经接受了答案。为了显示匹配和控制匹配的更多扩展,这可能在将来帮助您:
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);
将输出:
http://link.com/whatever/
Doublets无关紧要在你的情况下。如果你有这个字符串:
Doublets won't matter in your situation. If you have this string:
var url = 'http://link.com//om/om/om/om/om///';
您的 set
数组将包含多个米//
。有点多余,因为循环会看到该变量几次。好处是 String.replace()
如果什么都没找到则不替换任何内容,所以不会造成任何伤害。
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
中删除重复项,但这几乎需要相同数量的资源,只需让for循环遍历它们。
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.
祝你好运!
这篇关于用于匹配URL中的多个正斜杠的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!