Search code examples
ruby-on-railsrubyregexgsubslash

How to remove random excess of slashes from url?


How to remove random excess of slashes from url or just validate it?

For example,

valid statements:

http://domain.com/url/url2

https://domain.com/url/url2

www.domain.com/url/url2

invalid statements:

http://domain.com//url/url2

https://domain.com/////url/url2

www.domain.com/url/////////url2

Thanks for help!


Solution

  • Use regular expressions:

    require 'uri'
    url = URI.parse('https://domain.com/////url/url2')
    url.path.gsub! %r{/+}, '/'
    p url.to_s