Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java equivalent to JavaScript unescape function

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!

like image 355
Fernando Magalhães Avatar asked Nov 25 '11 20:11

Fernando Magalhães


1 Answers

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

like image 53
machinery Avatar answered Sep 27 '22 20:09

machinery