Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
134
rated 0 times [  135] [ 1]  / answers: 1 / hits: 24133  / 11 Years ago, tue, march 26, 2013, 12:00:00

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/


More From » regex

 Answers
3

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!


[#79347] Monday, March 25, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
pierre

Total Points: 716
Total Questions: 128
Total Answers: 102

Location: Djibouti
Member since Sun, Feb 27, 2022
2 Years ago
;