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
I think a regex is a little bit of an overkill in this situation. If you just want to remove all the quotes in your string I would use this code:
details = details.replace("\"", "");
Would not that have to be:
.replaceAll("\"","\\\\\"")
FIVE backslashes in the replacement String.
The following regex will work for both:
text = text.replaceAll("('|\")", "\\\\$1");
To make it work in JSON, you need to escape a few more character than that.
myString.replace("\\", "\\\\")
.replace("\"", "\\\"")
.replace("\r", "\\r")
.replace("\n", "\\n")
and if you want to be able to use json2.js
to parse it then you also need to escape
.replace("\u2028", "\\u2028")
.replace("\u2029", "\\u2029")
which JSON allows inside quoted strings, but which JavaScript does not.
I know the answer is already accepted here, but I just wanted to share what I found when I tried to escape double quotes and single quotes.
Here's what I have done: and this works :)
to escape double quotes:
if(string.contains("\"")) {
string = string.replaceAll("\"", "\\\\\"");
}
and to escape single quotes:
if(string.contains("\'")) {
string = string.replaceAll("\'", "\\\\'");
}
PS: Please note the number of backslashes used above.
This is to remove double quotes in a string.
str1 = str.replace(/"/g, "");
alert(str1);