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!

Upvotes: 4

Views: 11877

Answers (4)

machinery
machinery

Reputation: 3945

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

Upvotes: 10

feder
feder

Reputation: 1795

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

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

Upvotes: 0

Mark Byers
Mark Byers

Reputation: 838896

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

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

Upvotes: 4

Nrj
Nrj

Reputation: 6841

Try this

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

Upvotes: 1

Related Questions