Replace all double quotes within String

前端 未结 8 1170
轻奢々
轻奢々 2020-12-13 06:00

I am retrieving data from a database, where the field contains a String with HTML data. I want to replace all of the double quotes such that it can be used for parseJS

相关标签:
8条回答
  • 2020-12-13 06:37

    Here's how

    String details = "Hello \"world\"!";
    details = details.replace("\"","\\\"");
    System.out.println(details);               // Hello \"world\"!
    

    Note that strings are immutable, thus it is not sufficient to simply do details.replace("\"","\\\""). You must reassign the variable details to the resulting string.


    Using

    details = details.replaceAll("\"","&quote;");
    

    instead, results in

    Hello &quote;world&quote;!
    
    0 讨论(0)
  • 2020-12-13 06:41
    String info = "Hello \"world\"!";
    info = info.replace("\"", "\\\"");
    
    String info1 = "Hello "world!";
    info1 = info1.replace('"', '\"').replace("\"", "\\\"");
    

    For the 2nd field info1, 1st replace double quotes with an escape character.

    0 讨论(0)
提交回复
热议问题