admin管理员组

文章数量:1253385

Is there any function in Java programming language that is equivalent to JavaScript unescape function? That is, if my input is the string "I%20need%20help%21" the output must be "I need help!", for example.

Thanks!

Is there any function in Java programming language that is equivalent to JavaScript unescape function? That is, if my input is the string "I%20need%20help%21" the output must be "I need help!", for example.

Thanks!

Share Improve this question asked Nov 25, 2011 at 20:21 Fernando MagalhãesFernando Magalhães 5712 gold badges9 silver badges17 bronze badges 1
  • note that neither JS unescape nor URLDecoder are RFC-3986 patible subbu/blog/2008/02/uri-escaping-and-javaneturlencoder – Oleg Mikheev Commented Nov 25, 2011 at 20:36
Add a ment  | 

4 Answers 4

Reset to default 10

From my experience URLDecoder.decode might fail if there are non-ASCII characters in the encoded string. For example this code:

URLDecoder.decode("%u017C", "UTF-8"); // %u017C is the result of running in Javascript escape('ż')

throws the following exception:

Exception in thread "main" java.lang.IllegalArgumentException: URLDecoder: Illegal hex characters in escape (%) pattern - For input string: "u0"

The best way of solving this issue that I know of (though clumsy) is just running Javascript in Java :(

String jsEscapedString = "%u017C";
ScriptEngineManager factory = new ScriptEngineManager();
ScriptEngine engine = factory.getEngineByName("JavaScript");
String result = (String) engine.eval("unescape('" + jsEscapedString + "')");

BTW solution inspired by Siva R Vaka's post

You could use URLDecoder. Assuming you are using UTF-8:

String result = URLDecoder.decode(s, "UTF-8");

Try this

URLDecoder dec = new URLDecoder();
        String val = dec.decode("I%20need%20help%21","UTF-8");
        System.out.println(val);

That is fine @Nrj, but developers are to invoke it staticly.

URLDecoder.decode("I%20need%20help%21","UTF-8");

本文标签: Java equivalent to JavaScript unescape functionStack Overflow