How can I remove multiple trailing slashes from a URL in Ruby

What I'm trying to achieve here is to say that we have two example URLs:

url1 = "http://emy.dod.com/kaskaa/dkaiad/amaa//////////" url2 = "http://www.example.com/" 

How can I extract striped urls down?

 url1 = "http://emy.dod.com/kaskaa/dkaiad/amaa" url2 = "http://http://www.example.com" 

Ruby's URI.parse deactivates a certain type of malformed URL, but is ineffective in this case.

If we use a regular expression, then /^(.*)\/$/ removes one slash / from url1 and is invalid for url2 .

Does anyone know how to handle this type of URL parsing?

Here I do not want my system to http://www.example.com/ and http://www.example.com as two different URLs. The same goes for http://emy.dod.com/kaskaa/dkaiad/amaa//// and http://emy.dod.com/kaskaa/dkaiad/amaa/ .

+6
ruby regex url-parsing malformed
source share
2 answers

If you just need to remove all slashes from the end of the url string, you can try the following regular expression:

 "http://emy.dod.com/kaskaa/dkaiad/amaa//////////".sub(/(\/)+$/,'') "http://www.example.com/".sub(/(\/)+$/,'') 

/(\/)+$/ - this regular expression finds one or more slashes at the end of a line. Then we replace this correspondence with an empty string.

Hope this helps.

+23
source share

Although this thread is a little old and the top answer is not bad, but I suggest another way to do this:

 /^(.*?)\/$/ 

You can see it in action here: https://regex101.com/r/vC6yX1/2

*? magic here *? which makes a lazy coincidence. Thus, the whole expression can be translated as:

Match as many characters as possible and grab them, while at the end there will be as much slash as possible.

This means that in simpler English, all trailing slashes are removed.

+4
source share

All Articles