Ceryl
Ceryl

Reputation: 73

Replace ' with \' in C#

In this variable, i would like to add some \ before every '.

string html = 
    "<a href=\"annee-prochaine.html\">Calendrier de l'annee prochaine</a>"

html = html.Replace("'", "\'"); //No change
html = html.Replace("\'", "\'"); //No change

html = html.Replace("\'", "\\'");
//html => <a href=\"annee-prochaine.html\">Calendrier de l\\'annee prochaine</a>
html = html.Replace("\'", @"\'");
//html => <a href=\"annee-prochaine.html\">Calendrier de l\\'annee prochaine</a>

I would like to get that after Replace :

//html => <a href=\"annee-prochaine.html\">Calendrier de l\'annee prochaine</a>

Any ideas ?

Thanks!

Upvotes: 5

Views: 223

Answers (5)

Jon Skeet
Jon Skeet

Reputation: 1500385

I strongly suspect that you're looking at the strings in the debugger, which is why you're seeing doubled backslashes.

This version is absolutely fine:

html = html.Replace("\'", "\\'");

(The one using the verbatim string literal would be fine too.) Rather than looking at it in the debugger, log it or just serve it, and everything should be fine.

The fact that you're seeing it for the double-quote as well is further evidence of this. For example, this string:

string html = "<a href=\"anne...";

... does not contain a backslash, but your diagnostics are showing it, which is what I'd expect in a debugger.

Upvotes: 8

user1610015
user1610015

Reputation: 6678

Either of these lines:

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

Should do what you want. Maybe the debugger is telling you there are double \ characters, but in reality there is only one.

EDIT: sorry, actually it should be "'" as the first argument.

Upvotes: 0

Felipe Oriani
Felipe Oriani

Reputation: 38598

Try this:

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

Upvotes: 1

3Dave
3Dave

Reputation: 29041

 string html = "<a href=\"annee-prochaine.html\">Calendrier de l'annee prochaine</a>"

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

Upvotes: 1

Nick Larsen
Nick Larsen

Reputation: 18877

The backslash character is an escape character, so you either need to put 2 of them, or use the @ string modifier which ignores escaping.

html=html.Replace("'", "\\'"); // this should work
html=html.Replace("'", @"\'"); // or this

Upvotes: 7

Related Questions