Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't decodeURI("a+b") == "a b"?

Tags:

I'm trying to encode URLs in Ruby and decode them with Javascript. However, the plus character is giving me weird behavior.

In Ruby:

[Dev]> CGI.escape "a b" => "a+b" [Dev]> CGI.unescape "a+b" => "a b" 

So far so good. But what about Javascript?

>>> encodeURI("a b") "a%20b" >>> decodeURI("a+b") "a+b" 

Basically I need a method of encoding / decoding URLs that works the same way in Javascript and Ruby.

Edit: decodeURIComponent is no better:

>>> encodeURIComponent("a b") "a%20b" >>> decodeURIComponent("a+b") "a+b" 
like image 311
Tom Lehman Avatar asked Dec 26 '10 20:12

Tom Lehman


People also ask

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.

What is decodeURI?

The decodeURI() function decodes a Uniform Resource Identifier (URI) previously created by encodeURI() or by a similar routine.

What does decode URI component do?

The decodeURIComponent() function decodes a Uniform Resource Identifier (URI) component previously created by encodeURIComponent or by a similar routine.

What is encodeURIComponent Javascript?

The encodeURIComponent() 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).


2 Answers

+ is not considered a space. One workaround is to replace + with %20 and then call decodeURIComponent

Taken from php.js' urldecode:

decodeURIComponent((str+'').replace(/\+/g, '%20')); 
like image 107
Matt Avatar answered Sep 21 '22 15:09

Matt


From MDC decodeURI:

Does not decode escape sequences that could not have been introduced by encodeURI.

From MDC encodeURI:

Note that encodeURI by itself cannot form proper HTTP GET and POST requests, such as for XMLHTTPRequests, because "&", "+", and "=" are not encoded

like image 38
user113716 Avatar answered Sep 20 '22 15:09

user113716