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
4 Answers
Reset to default 10From 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
版权声明:本文标题:Java equivalent to JavaScript unescape function - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1740757096a2281438.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论