0

I am trying to remove the webpage part of the URL

For example,

www.example.com/home/index.html 

to

www.example.com/home 

any help appreciated.
Thanks

1

3 Answers 3

10

It's probably a good idea not to use regular expressions when possible. You may summon Cthulhu. Try using the URI library that's part of the standard library instead.

require "uri"
result = URI.parse("http://www.example.com/home/index.html")
result.host # => www.example.com
result.path # => "/home/index.html"
# The following line is rather unorthodox - is there a better solution?
File.dirname(result.path) # => "/home"
result.host + File.dirname(result.path) # => "www.example.com/home"
Sign up to request clarification or add additional context in comments.

2 Comments

+1 URL's are not regular, cannot parse them with regex, use URI lib
Addressable::URI is another good URI module for Ruby and is a bit more full-featured. Ruby's built-in URI should be sufficient for this purpose though. github.com/sporkmonger/addressable
0

If your heart is set on using regex and you know that your URLs will be pretty straight forward you could use (.*)/.* to capture everything before the last / in your URL.

irb(main):007:0> url = "www.example.com/home/index.html"
=> "www.example.com/home/index.html"
irb(main):008:0> regex = "(.*)/.*"
=> "(.*)/.*"
irb(main):009:0> url =~ /#{regex}/
=> 0
irb(main):010:0> $1
=> "www.example.com/home"

Comments

0
irb(main):001:0> url="www.example.com/home/index.html"
=> "www.example.com/home/index.html"
irb(main):002:0> url.split("/")[0..-2].join("/")
=> "www.example.com/home"

3 Comments

While this technically works, it will break on different depth URLs (/home/index.html vs /admin/users/index.html). That's why URI.parse is better.
@Jason: Under what circumstance would 0..-2 break?
I re-read this and you're right, 0..-2 should always work. I still vote for using URI.parse though.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.