Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I raw URL encode/decode in JavaScript and Ruby to get the same values in both?

I am working on a web application where I have to encode and decode a string at the JavaScript side and Ruby backend of the code. the only problem is that the escape methods for JavaScript and Ruby have a small difference. in JavaScript the " " is treated as "%20" but in ruby the " " is encoded to "+".

Any way to solve this? Another Ruby method to encode a string in raw URL encode?

After some Selenium testing I noticed that for some reason the URI.unescape mixes up between the "£" and the "?". If I use encodeURIComponent("£"); in JavaScript and then URI.unescape("%C2%A3") in Ruby which is the value we get when we encode the "£" sign, I get the "?" sign returned. Any solution?

like image 463
Mo. Avatar asked May 14 '10 12:05

Mo.


People also ask

How do you decode or encode a URL in JavaScript?

The decodeURIComponent() function is used to decode some parts or components of URI generated by encodeURIComponent(). Decoding in Javascript can be achieved using decodeURI function. It takes encodeURIComponent(url) string so it can decode these characters.

What is difference between decodeURI and decodeURIComponent?

decodeURI is used to decode complete URIs that have been encoded using encodeURI . Another similar function is decodeURIComponent . The difference is that the decodeURIComponent is used to decode a part of the URI and not the complete URI.

How do I use encodeURI in JavaScript?

The encodeURI() function encodes a URI by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character (will only be four escape sequences for characters composed of two "surrogate" characters).

Does browser automatically decode URL?

Many browsers automatically encode and decode the URL and the response string. E.g., A space " " is encoded as a + or %20.


2 Answers

URI.escape was deprecated, an alternative is ERB::Util.url_encode.

ERB::Util.url_encode(foo)

If you are using it inside an .erb file you can do:

u(foo)
like image 169
TheVTM Avatar answered Sep 21 '22 02:09

TheVTM


Use

URI.escape(foo, Regexp.new("[^#{URI::PATTERN::UNRESERVED}]"))

in ruby, and

encodeURIComponent(foo); 

in javascript

Both these will behave equally and encode space as %20.

like image 30
Sean Kinsey Avatar answered Sep 23 '22 02:09

Sean Kinsey