I need a regular expression for replacing multiple forward slashes in a URL with a single forward slash, excluding the ones following the colon
e.g. http://link.com//whatever///
would become http://link.com/whatever/
I need a regular expression for replacing multiple forward slashes in a URL with a single forward slash, excluding the ones following the colon
e.g. http://link.com//whatever///
would become http://link.com/whatever/
I think this should work: /[^:](\/+)/
or /[^:](\/\/+)/
if you want only multiples.
It wont match leading //
but it looks like you're not looking for that.
To replace:
"http://test//a/b//d".replace(/([^:]\/)\/+/g, "$1") // --> http://test/a/b/d
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.
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.
Good luck!
result = subject.replace(/(?<!http:)\/*\//g, "/");
or (for http, https, ftp and ftps)
result = subject.replace(/(?<!(?:ht|f)tps?:)\/*\//g, "/");
The original accepted answer does a sufficient job at replacing, but not for matching. And the currently accepted answer matches the character before duplicate slashes, also not good for matching.
Using a negative lookbehind to exclude the protocol from the match (?<!:)
, and a curly bracket quantifier to match 2 to infinite slashes \/{2,}
does the job to both match and replace.
(?<!:)\/{2,}
let str = 'https://test.example.com:8080//this/is//an/exmaple///';
document.write('Original: ' + str + '<br><br>');
document.write('Matches: ' + str.match(/(?<!:)\/{2,}/g) + '<br><br>');
document.write('Replaced: ' + str.replace(/(?<!:)\/{2,}/g, '/'));