更新时间:2022-06-03 22:03:52
您已经接受了答案。为了显示匹配和控制匹配的更多扩展,这可能在将来帮助您:
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.
祝你好运!