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."
3
  • 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, 2012 at 22:14
  • @SirPentor - Indeed. I had it right, but, the debugger was showing me a different value. May 24, 2012 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? (as an answer covers the most common cases and the external reference the rest). Sep 21, 2022 at 14:14

5 Answers 5

89

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

s = s.Replace("'", @"\'");
7
  • I had tried that previously, and that did not work either. It results in: John\\'s book. May 23, 2012 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, 2012 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, 2012 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. May 24, 2012 at 14:27
  • 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, 2014 at 10:10
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
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");
        }
    }
2
  • 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 5, 2017 at 21:49
  • @sapbucket as noted, this is for mysql. You could change it to insert the correct esc sequence.
    – JohnP
    Dec 5, 2017 at 22:15
3

The simplest one would be

Server.HtmlEncode(varYourString);
0
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.