43

It pains me to ask this, but, for some reason I have not been able to get this to work (it's late in the day, yes, that's my excuse).

Let's say I have this string:

s = "John's book."

Using the replace method from the object String, I want to turn it into this:

s = "John\'s book."

I would have expected this code to give me what I want:

s = s.Replace("'", "\\'")

But, that results in:

"John\\'s book."
Justin Helgerson
  • 24,900
  • 17
  • 97
  • 124
  • 1
    what you're doing looks like it should work. Is that result from the debugger? I think VS will "help" by showing a '\\' instead of a '\'. – SirPentor May 23 '12 at 22:14
  • @SirPentor - Indeed. I had it right, but, the debugger was showing me a different value. – Justin Helgerson May 24 '12 at 14:27
  • This is in the top 2 for a search engine hit for "C# escape single quotes"... What is the canonical question for escaping string in C#? It definitely exists. Candidate: *[Can I escape a double quote in a verbatim string literal?](https://stackoverflow.com/questions/1928909/can-i-escape-a-double-quote-in-a-verbatim-string-literal/1928943#1928943)* (as an answer covers the most common cases and the external reference the rest). – Peter Mortensen Sep 21 '22 at 14:14

5 Answers5

87

Do this so you don't have to think about it:

s = s.Replace("'", @"\'");
BeemerGuy
  • 8,139
  • 2
  • 35
  • 46
  • I had tried that previously, and that did not work either. It results in: `John\\'s book.` – Justin Helgerson May 23 '12 at 22:14
  • 9
    I think you may just be viewing it in the debugger/inspector which will show it escaped (twice) but if you do `Console.Write()` it should output correctly. – lukiffer May 23 '12 at 22:16
  • 1
    You're probably debugging and looking at the result by hovering over `s` in Visual Studio... yes, that shows the escapes; coz that's the truth. But if you output the string somewhere (a text box, or in the console) it'll come out with a single slash. – BeemerGuy May 23 '12 at 22:17
  • I guess I had it right all along. Although I don't agree that what the debugger was showing is "the truth", because it's not what the value truly is. – Justin Helgerson May 24 '12 at 14:27
  • Anyone care to modify this to explain why the literal works when the standards string notatiton does not? – Manuel Hernandez Jun 28 '14 at 18:02
  • 2
    @manuelhe; both `s.Replace("'", @"\'");` and `s.Replace("'", "\\'");` will give the same result -- the difference is in the debugger itself; it shows the string value as `"John\\'s book."` with an extra slash. But if you output this in Console or a file, you will see the real result `"John\'s book."`. – BeemerGuy Jun 29 '14 at 10:10
  • Is this supposed to work for http header values? I tried but it didn't. – Psddp Apr 25 '18 at 16:13
8

Just to show another possible solution if this is pertaining to ASP.NET MVC (ASP.NET MVC 5 or later):

var data= JSON.parse('@Html.Raw(HttpUtility.JavaScriptStringEncode(JsonConvert.SerializeObject(Model.memberObj)))');

This allows you to escape and pass data to views as JavaScript. The key part is:

HttpUtility.JavaScriptStringEncode
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Richard Duerr
  • 566
  • 8
  • 24
4

I have a quick-and-dirty function to escape text before using it in a MySQL insert clause. This might help:

    public static string MySqlEscape(Object usString)
    {
        if (usString is DBNull)
        {
            return "";
        }
        else
        {
            string sample = Convert.ToString(usString);
            return Regex.Replace(sample, @"[\r\n\x00\x1a\\'""]", @"\$0");
        }
    }
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
JohnP
  • 402
  • 1
  • 8
  • 25
  • This does not work for me. I'm using C#, Sqlite, etc. What I get is a backslash in front of the single quote, which isn't how Sqlite escapes single quotes. – sapbucket Dec 05 '17 at 21:49
  • @sapbucket as noted, this is for mysql. You could change it to insert the correct esc sequence. – JohnP Dec 05 '17 at 22:15
3

The simplest one would be

Server.HtmlEncode(varYourString);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
0

Just to let you know in this case

string q = "John's book";
string s = s.Replace("'", "\\'");
string t = s.Replace("'", "\\\'");

s and t will display same thing;

https://dotnetfiddle.net/OwGyHW

N Djel Okoye
  • 950
  • 12
  • 10