I wrote it because it became necessary to perform escaping in an environment where external libraries cannot be used. Environment is Windows and Java 10
Since default arguments cannot be used for java, it seems better to overload and create ʻENT_QUOTES` as a character string argument if you think about character codes in the future.
function
public class Escape{
/**
& to &
" to " if flag.equals("ENT_COMPAT") flag.equals("ENT_QUOTES")
' to ' if flag.equals("ENT_QUOTES")
< to <
> to >
*/
public static String htmlspecialchars(String s, String flag){
String ret = s.replace("&","&").replace("<","<").replace(">",">");
if(flag.equals("ENT_COMPAT")){
return ret.replace("\"", """);
}else if(flag.equals("ENT_QUOTES")){
return ret.replace("'", "'").replace("\"",""");
}else if(flag.equals("ENT_NOQUOTES")){
return ret;
}
return ret;
}
}
It's not very pretty, I felt that return ret;
would be fine if ʻENT_COMPAT and ʻENT_QUOTES
were not specified.
main
public static void main(String[] args){
System.out.println(htmlspecialchars("<script>alert(\"1\");</script>","ENT_COMPAT"));
System.out.println(htmlspecialchars("<script>alert(\"1\");</script>","ENT_NOQUOTES"));
System.out.println(htmlspecialchars("<script>alert('1');</script>","ENT_QUOTES"));
}
result
>java Escape
<script>alert("1");</script>
<script>alert("1");</script>
<script>alert('1');</script>
Recommended Posts