5

I want to decode a string that has been encoded using the java.net.URLEncoder.encode() method.

I tried using the unescape() function in javascript, but a problem occurs for blank spaces because java.net.URLEncoder.encode() converts a blank space to '+' but unescape() won't convert '+' to a blank space.

hopper
13.5k7 gold badges52 silver badges54 bronze badges
asked Nov 15, 2008 at 9:53

4 Answers 4

1

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

answered Nov 15, 2008 at 9:59
Sign up to request clarification or add additional context in comments.

1 Comment

Just because it takes a string as argument !-)
1

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.

answered Nov 15, 2008 at 11:38

Comments

1

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).

answered Nov 15, 2008 at 20:40

Comments

1

Try

var decoded = decodeURIComponent(encoded.replace(/\+/g," "));
answered Mar 21, 2009 at 1:10

1 Comment

This did convert '+' to a blank space. Worked perfectly. Thanks :)

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.