Justin Helgerson
Justin Helgerson

Reputation: 25551

Turning a single quote into an escaped single quote within a string

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."

Upvotes: 44

Views: 121480

Answers (5)

Richard Duerr
Richard Duerr

Reputation: 596

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

Upvotes: 10

The simplest one would be

Server.HtmlEncode(varYourString);

Upvotes: 3

JohnP
JohnP

Reputation: 402

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");
        }
    }

Upvotes: 4

N Djel Okoye
N Djel Okoye

Reputation: 1078

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

Upvotes: 0

BeemerGuy
BeemerGuy

Reputation: 8279

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

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

Upvotes: 90

Related Questions