Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escaping URL's (without double escaping)

Tags:

browser

url

ruby

How do I escape a URL as needed, without double escaping?

Is there a Ruby library that already does this? I wonder what algorithm WebKit or Chrome uses.

Two examples:

  • This URL is not valid, since the % is not escaped: http://x.co/op&k=21%. If you type it into the URL bar, it knows to escape it. (It is escaping the '%' behind the scenes, right?)

  • If you type http://localhost:3000/?s=hello%20world into a browser, it knows to not escape %20 again.

I want to reuse great code that has already worked the edge cases that browsers have to handle. I don't mind calling an external library if necessary.

Update: Yes, I know about URI.parse. No need to show me the syntax. My question is harder than that.

like image 442
David J. Avatar asked Mar 05 '26 02:03

David J.


1 Answers

So far, the winners are:

  • Addressable::URI#normalize: "Returns a normalized URI object. NOTE: This method does not attempt to fully conform to specifications. It exists largely to correct other people’s failures to read the specifications, and also to deal with caching issues since several different URIs may represent the same resource and should not be cached multiple times."

  • Addressable::URI.heuristic_parse: "Converts an input to a URI. The input does not have to be a valid URI -- the method will use heuristics to guess what URI was intended. This is not standards-compliant, merely user-friendly."

like image 136
David J. Avatar answered Mar 07 '26 22:03

David J.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!