Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace all double quotes within String

Tags:

java

regex

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 parseJSON of jQuery.

Using Java, I am trying to replace the quotes using..

details.replaceAll("\"","\\\"");   //details.replaceAll("\"","&quote;"); details.replaceAll("\"","&#34"); 

The resultant string doesn't show the desired change. An O'Reilly article prescribes using Apache string utils. Is there any other way??

Is there a regex or something that I could use?

like image 564
MalTec Avatar asked Mar 19 '11 12:03

MalTec


People also ask

How do you replace double quotes?

Use the String. replaceAll() method to replace single with double quotes, e.g. const replaced = str. replaceAll("'", '"'); . The replaceAll method will return a new string where all occurrences of single quotes are replaced with double quotes.

How can I replace double quotes in a string in Java?

Add double quotes to String in java If you want to add double quotes(") to String, then you can use String's replace() method to replace double quote(") with double quote preceded by backslash(\").

How do you remove double quotes from a replacement string?

Use the String. replaceAll() method to remove all double quotes from a string, e.g. str. replaceAll('"', '') . The replace() method will return a new string with all double quotes removed.

How do you replace double quotes in a string in Python?

So here in our first statement, we first generate a string with double quotes. Then we call the rstrip() function and pass ('\')as a parameter to remove double-quotes. Then we use two print functions. The first one displays the original string and the second one displays the new filtered string.


1 Answers

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;! 
like image 154
aioobe Avatar answered Sep 28 '22 16:09

aioobe