Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex for matching multiple forward slashes in URL

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/

like image 796
geochr Avatar asked Mar 26 '13 13:03

geochr


People also ask

How do you handle forward slash in regex?

The forward slash character is used to denote the boundaries of the regular expression: ? The backslash character ( \ ) is the escaping character. It can be used to denote an escaped character, a string, literal, or one of the set of supported special characters.

What is a good regex to match a URL?

@:%_\+~#= , to match the domain/sub domain name.

What does regex 0 * 1 * 0 * 1 * Mean?

Basically (0+1)* mathes any sequence of ones and zeroes. So, in your example (0+1)*1(0+1)* should match any sequence that has 1. It would not match 000 , but it would match 010 , 1 , 111 etc. (0+1) means 0 OR 1. 1* means any number of ones.

Does * match everything in regex?

Throw in an * (asterisk), and it will match everything. Read more. \s (whitespace metacharacter) will match any whitespace character (space; tab; line break; ...), and \S (opposite of \s ) will match anything that is not a whitespace character.


1 Answers

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

Working Demo

like image 115
Halcyon Avatar answered Sep 30 '22 19:09

Halcyon