views:

562

answers:

4
+2  Q: 

URL decoding

I want to decode string which is encoded using java.net.URLEncoder.encode() function.

i tried using unescape() function in java script.

but problem occure for blank space because java.net.URLEncoder.encode() converts blank space to '+' and unescape() function wont convert '+' to blank space.

+2  A: 

Try decodeURI("") or decodeURIComponent("") !-)

roenving
why ("") ? :)
Vinko Vrsalovic
Just because it takes a string as argument !-)
roenving
+2  A: 

Using JavaScript's escape/unescape function is almost always the wrong thing, it is incompatible with URL-encoding or any other standard encoding on the web. Non-ASCII characters are treated unexpectedly as well as spaces, and older browsers don't necessarily have the same behaviour.

As mentioned by roenving, the method you want is decodeURIComponent(). This is a newer addition which you won't find on IE 5.0, so if you need to support that browser (let's hope not, nowadays!) you'd need to implement the function yourself. And for non-ASCII characters that means you need to implement a UTF-8 encoder. Code is available if you need it.

bobince
+1  A: 

decodeURI[Component] doesn't handle + as space either (at least on FF3, where I tested).

Simple workaround:

alert(decodeURIComponent('http://foo.com/bar+gah.php?r=%22a+b%22&d=o%e2%8c%98o'.replace(/\+/g, '%20')))

Indeed, unescape chokes on this URL: it knows only UTF-16 chars like %u2318 which are not standard (see Percent-encoding).

PhiLho
A: 

Try

var decoded = decodeURIComponent(encoded.replace(/\+/g," "));