I seem to be having issues. I have a query string that has values that can contain single quotes. This will break the query string. So I was trying to do a replace to change '
to \'
.
Here is a sample code:
"This is' it".replace("'", "\'");
The output for this is still:
"This is' it".
It thinks I am just doing an escape character for the quote.
So I tried these two pieces of code:
"This is' it".replace("'", "\\'"); // \\ for the backslash, and a ' char
"This is' it".replace("'", "\\\'"); // \\ for the backslash, and \' for the ' char
Both of the above STILL results in the same output:
"This is' it"
I can only seem to get this to actually spit out a slash with:
"This is' it".replace("'", "\\\\'");
Which results in:
"This is\\' it"
Any suggestions? I just want to replace a '
with \'
.
It doesn't seem like it should be that difficult.
Remember that stringToEdit.replaceAll(String, String)
returns the result string. It doesn't modify stringToEdit because Strings are immutable in Java. To get any change to stick, you should use
stringToEdit = stringToEdit.replaceAll("'", "\\'");
Use "This is' it".replace("'", "\\'")
If you want to use it in JavaScript then you can use
str.replace("SP","\\SP");
But in Java
str.replaceAll("SP","\\SP");
will work perfectly.
SP: special character
Otherwise you can use Apache's EscapeUtil. It will solve your problem.
Example :
String teste = " 'Bauru '";
teste = teste.replaceAll(" ' ","");
JOptionPane.showMessageDialog(null,teste);
I have used a trick to handle the apostrophe special character. When replacing ' for \' you need to place four backslashes before the apostrophe.
str.replaceAll("'","\\\\'");
I have used
str.replace("'", "");
to replace the single quote in my string. Its working fine for me.
Source: Stackoverflow.com