1

我正在编写一个 Java 代码,通过它创建一个 JavaScript 文件。在脚本文件中,我想写

var alertData = "Following characters are not allowed for value. [ $ & + , / : ; =? @ \" < > #    % { } | \\ ~ ^ [ ] ` ]";

当我编译代码并调用方法来创建文件时,

Syntax Error: syntax error: > is not valid.

有人可以帮忙吗?

更多代码

StringBuilder sb = new StringBuilder(100);
sb.append("var validationAlertForValues = \"");
sb.append(("Following characters are not allowed for value. [ $ & + , / : ; =? @ \" < > # % { } | \\ ~ ^ [ ] ` ]"));
sb.append("\";\n    var validationAlertForKeys = \"");
sb.append(("Following characters are not allowed for key name.  [ $ & + , / : ; =? @ \" # % { } | ~ ^ [ ] ` &lt;space&lt; ] "));

 FileWriter fstream = null;
 BufferedWriter out = null;
 try {
   fstream = new FileWriter(filePath);
   out = new BufferedWriter(fstream);
   out.write(sb.toString());
        } catch (Exception e) {
            log.error("Exception in making JS", e);
        }
4

2 回答 2

3

Use this Apache CommonLang StringEscapeUtils.

There are classes there to escape different type of input. Here is a sample i found.

import org.apache.commons.lang.StringEscapeUtils;

public class MainClass {
    public static void main(String[] args) {
        String strHTMLInput = "<P>MyName<P>";
        String strEscapeHTML = StringEscapeUtils.escapeHtml(strHTMLInput);
        String strUnEscapeHTML = StringEscapeUtils.unescapeHtml(strEscapeHTML);
        System.out.println("Escaped HTML >>> " + strEscapeHTML);
        System.out.println("UnEscaped HTML >>> " + strUnEscapeHTML);
    }
}
于 2013-08-27T11:08:00.323 回答
1

您使用\"的是转义字符符号。尝试使用\\".

于 2013-08-27T10:56:22.350 回答