Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

string.Replace does not work for quote

((string)dt.Rows[i][1]).Replace("'", "\\'")

I want the result that if any string have quote it change it into slash quote, e.g. John's -> John\'s

but the above replace function is not working fine. it results like John\\'s

but if we change the code to

((string)dt.Rows[i][1]).Replace("'", "\'")

it gives the Result like John's

does change it anyway.

like image 542
Azhar Avatar asked Jun 07 '10 13:06

Azhar


People also ask

How do you replace a string in a quote?

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

Why is string replace not working Python?

1 Answer. You are facing this issue because you are using the replace method incorrectly. When you call the replace method on a string in python you get a new string with the contents replaced as specified in the method call. You are not storing the modified string but are just using the unmodified string.

How do you escape quotation marks in a string?

You can put a backslash character followed by a quote ( \" or \' ). This is called an escape sequence and Python will remove the backslash, and put just the quote in the string. Here is an example. The backslashes protect the quotes, but are not printed.

Can you have a string with a quote inside it?

To place quotation marks in a string in your code In Visual Basic, insert two quotation marks in a row as an embedded quotation mark. In Visual C# and Visual C++, insert the escape sequence \" as an embedded quotation mark.


2 Answers

Because the backslash is the escape character, you need to tell it you want to treat it like a literal string. You do this by prepending an @ to the string:

((string)dt.Rows[i][1]).Replace("'", @"\'") 
like image 73
Paul Kearney - pk Avatar answered Sep 23 '22 13:09

Paul Kearney - pk


Try a double backslash.

\\

Just one backslash is an escape; two is an actual backslash.

like image 45
Dean J Avatar answered Sep 21 '22 13:09

Dean J