8

Dumb question probably, but can't seem to get it to work. I need to Replace quotes from a textbox with \" so it will export to excel correctly. I'm trying:

[Note].Text).Replace("\"", "\"")

Am I doing it completely wrong? Wouldn't surprise me if I am. Any recommendations on how to do this?

Thanks!

2
  • 4
    ...Replace("\"", "\\\"") (gotta escape the backslash and quote in replacement)
    – 0b10011
    Jan 9, 2012 at 16:20
  • Are you sure Excel needs \" ? I would expect that no escaping is needed. Concrete example? Jan 9, 2012 at 16:27

6 Answers 6

14
String quotedText = "\"Hello, world!\"";
// quotedText = "Hello, World!"
String newQuotedText = quotedText.replace("\"", "\\\"");
// newQuotedText = \"Hello, World!\"

You need to escape the backslash you want transferred to the new value as well.

2

.Replace("\"", "\\\"")

\\ means \ character. You must escape it too, so it can be shown.

2

You have to escape the backslash as well as the quote:

mystring.Replace("\"", "\\\"")
1
  • I was trying to do exactly the opposite replace and was getting cross-eyed over it. Thanks for clarifying it for me! Jan 26, 2020 at 17:33
0
Replace("\"", "\\\"");

You need 3 \ for the replacement string, the first one to escape the second one so that a \ will appear in the value, and the third one to escape the quotes

0

Lazy, but i'm almost sure it works.

Replace("\"","\\" + "\"");
0

This works

string s = "diana\"s here";
string s2=s.Replace ("\"","\\\"");

Your Answer

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