简体   繁体   English

Java相当于JavaScript的unescape函数

[英]Java equivalent to JavaScript unescape function

Is there any function in Java programming language that is equivalent to JavaScript unescape function? Java编程语言中是否有与JavaScript unescape函数等效的函数? That is, if my input is the string "I%20need%20help%21" the output must be "I need help!", for example. 也就是说,如果我的输入是字符串“I%20need%20help%21”,则输出必须是“我需要帮助!”,例如。

Thanks! 谢谢!

From my experience URLDecoder.decode might fail if there are non-ASCII characters in the encoded string. 根据我的经验,如果编码字符串中存在非ASCII字符,则URLDecoder.decode可能会失败。 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 :( 解决这个问题的最好方法我知道(虽然笨拙)只是在Java中运行Javascript :(

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 BTW解决方案受Siva R Vaka的帖子启发

You could use URLDecoder . 您可以使用URLDecoder Assuming you are using UTF-8: 假设您使用的是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);

这很好@Nrj,但开发人员要静态调用它。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM