我需要一个正则表达式来替换带有单个正斜杠的URL中的多个正斜杠,不包括冒号后的斜杠
例如http://link.com//whatever///会成为http://link.com/whatever/
Hal*_*yon 31
我认为这应该有用:/[^:](\/+)/或者/[^:](\/\/+)/如果你只想要倍数.
它不匹配领先,//但看起来你不是在寻找它.
取代:
"http://test//a/b//d".replace(/([^:]\/)\/+/g, "$1") // --> http://test/a/b/d
Run Code Online (Sandbox Code Playgroud)
小智 2
因为您已经接受了答案。为了展示匹配和控制匹配的更多扩展,这可能会在将来帮助您:
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);
Run Code Online (Sandbox Code Playgroud)
将输出:
http://link.com/whatever/
Run Code Online (Sandbox Code Playgroud)
双峰在你的情况下并不重要。如果你有这个字符串:
var url = 'http://link.com//om/om/om/om/om///';
Run Code Online (Sandbox Code Playgroud)
您的set数组将包含多个m//. 有点多余,因为循环会多次看到该变量。好处是,String.replace()如果找不到任何内容,则不会替换任何内容,因此不会造成任何伤害。
您可以做的是从第一个中删除重复项set,但这几乎需要与仅让 for 循环遍历它们相同数量的资源。
祝你好运!
| 归档时间: |
|
| 查看次数: |
16531 次 |
| 最近记录: |