27

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
derekmw
  • 375
  • 1
  • 5
  • 13
  • 1
    Did you make a typo? I don't see a difference between the last two code snippets, and the latter's results seem to be what you want. – jwodder Jun 06 '11 at 21:35
  • 4
    "I have a query string" - did you mean a SQL query string? If so, use PreparedStatements and parameterized queries. Then you wouldn't have to deal with escaping these characters on your own. – Vineet Reynolds Jun 06 '11 at 21:35
  • I'm with jwodder on this. What you want and what you get appear to be the same. – MirroredFate Jun 06 '11 at 21:39

7 Answers7

36

First of all, if you are trying to encode apostophes for querystrings, they need to be URLEncoded, not escaped with a leading backslash. For that use URLEncoder.encode(String, String) (BTW: the second argument should always be "UTF-8"). Secondly, if you want to replace all instances of apostophe with backslash apostrophe, you must escape the backslash in your string expression with a leading backslash. Like this:

"This is' it".replace("'", "\\'");

Edit:

I see now that you are probably trying to dynamically build a SQL statement. Do not do it this way. Your code will be susceptible to SQL injection attacks. Instead use a PreparedStatement.

Asaph
  • 159,146
  • 25
  • 197
  • 199
  • 3
    You are assuming he means HTTP query strings. He might. He might not. – user207421 Jun 06 '11 at 21:38
  • @EJP: Yes. That's my assumption. I don't often hear the words "query string" in any other context. Let's wait and see if the OP clarifies otherwise. – Asaph Jun 06 '11 at 21:42
  • Just to clarify a bit, I am writing automation scripts that perform actions on a page. A web page I am testing has a drop down with values from populated from the database. So I grab the values from the database, randomly select one of the values from the result-set, and make the selection on the web page. The problem I am having is that some of the values in the result-set contain single quotes. – derekmw Jun 06 '11 at 21:45
  • @user770404: Are you building an http link or a SQL string? – Asaph Jun 06 '11 at 21:45
  • Because one drop down selection drives another drop down value, to make the script versatile, I then use the random value selected previously and plug it into another query. This causes problems if the previous value has a single quote as it terminates the query string I am passing. – derekmw Jun 06 '11 at 21:49
  • 1
    @user770404: So this is SQL then? Yes? If so, you are going about this wrong. You should be using a `PreparedStatement`. Your current strategy is susceptible to SQL injection attacks. – Asaph Jun 06 '11 at 21:52
  • "select column_Name from table_name where column_name = '" + rndQueryValue + "'" This is pretty much what I am doing. So you can see that if rndQueryValue contains any quotes, this query string breaks. So I was trying to do a replace on this rndQueryValue variable and replace ' with \' – derekmw Jun 06 '11 at 21:52
  • 1
    I completely agree if this was an application. As I mentioned, this is just a test script running locally to test a web application. – derekmw Jun 06 '11 at 21:53
  • @user770404: I think I know what your issue is: You're putting the extra backslash in your HTML form. Don't do it there. Instead, do it when you construct the SQL. Like this: `"select column_Name from table_name where column_name = '" + rndQueryValue.replace("'", "\\'") + "'"`. But again, this is horrible. SQL Injection. Oy... – Asaph Jun 06 '11 at 21:55
  • Hmm..I will give that a shot. I am using existing test framework, and upon closer look, the query string I build gets passed to a statement object. But SQL injection is not something that is a concern with this even if it was the case being that this is a test script grabbing values from our database to simulate users interacting with our application. – derekmw Jun 06 '11 at 22:02
  • 1
    Thanks Asaph. That seemed to work. If I perform the replace at the time of passing the combined string/variable to the statement, then the query runs properly. – derekmw Jun 06 '11 at 22:14
  • @derekmw: No problem. If you've found my answer helpful, please mark it correct by clicking the checkbox to the left of the answer. Thank you. – Asaph Jun 06 '11 at 22:24
5

Use "This is' it".replace("'", "\\'")

Marcelo
  • 11,218
  • 1
  • 37
  • 51
4

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("'","\\\\'");
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Sanjay Saini
  • 107
  • 1
  • 8
1

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
0

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("'", "\\'");
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Gooby
  • 70
  • 7
0

Example :

String teste = " 'Bauru '";

teste = teste.replaceAll("  '  ","");
JOptionPane.showMessageDialog(null,teste);
slfan
  • 8,950
  • 115
  • 65
  • 78
-1

I have used

str.replace("'", "");

to replace the single quote in my string. Its working fine for me.

FDinoff
  • 30,689
  • 5
  • 75
  • 96