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/
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!