0

I've tried different way but not working yet.

public String SuEscapeHTML(String text){
    text=text.replaceAll("/&/g", "&");
    // and how to deal with the double quote? text=text.replaceAll("/"/g", """);
    text=text.replaceAll("/'/g", "'");
    text=text.replaceAll("/</g", "&lt;");
    text=text.replaceAll("/>/g", "&gt;");
    text=text.replaceAll("/\\/g", "&#92;");
    System.out.println(text);
    return text;
}

nothing change by using this function.

So How to make it working?

chanjianyi
  • 607
  • 4
  • 15
  • 35
  • You aren't using a regular expression, so use `String.replace`; also there are several libraries that already do this (don't reinvent the wheel). – Elliott Frisch May 03 '16 at 03:24
  • 2
    See the documentation for `replaceAll`. It doesn't take `/.../g` – SLaks May 03 '16 at 03:24
  • @chanjianyi have you tried text=text.replaceAll("&", "&")? (Might want to do that one last) – Tibrogargan May 03 '16 at 03:28
  • what you are using in regex is syntax of javascript..that's not how you write regex in JAVA – rock321987 May 03 '16 at 03:36
  • @Slaks is right ... [this](https://docs.oracle.com/javase/) documentation, btw. (or change it to 7 for jdk 7, or if earlier... shoot yourself) – roberto tomás May 03 '16 at 03:37
  • I am sure answers in [this post](http://stackoverflow.com/questions/4874626/java-escape-html) can help you. – AKS May 03 '16 at 04:59
  • @Tibrogargan: If you leave the ampersand for last, it will mess up all the others. Of course, we're assuming there aren't any HTML escapes in the text already; that's another reason why you should use a dedicated tool for this. – Alan Moore May 03 '16 at 05:19

1 Answers1

2

The syntax of regex you are using is of JavaScript. This is how you will do it in Java

String text = "&>\"<\\'"; //You need to escape " in text also

System.out.println(text.replaceAll("&", "&amp;")); 
System.out.println(text.replaceAll("\"", "&quot;")); //For quotes
System.out.println(text.replaceAll("'", "&apos;"));
System.out.println(text.replaceAll("<", "&lt;"));
System.out.println(text.replaceAll(">", "&gt;"));
System.out.println(text.replaceAll("\\\\", "&#92;"));

Ideone Demo

rock321987
  • 10,942
  • 1
  • 30
  • 43