i need a regex in c# that will escape double quotes inside string literal. so if i have this string: “How about “this” and how about “that””. i will be able to use it in javascript without errors. because i am writing this literal to the page as js var.
EDIT: i will try to explain more about the problem.
i writing messege to the page like this:
string UserMsg = GetMessageText(999);
StringBuilder script = new StringBuilder();
script.AppendFormat("var UserMsg =\"{0}\";{1}", UserMsg, Environment.NewLine);
ScriptManager.RegisterClientScriptBlock(this, GetType(), "scriptparams", script.ToString(),true);
now lets say messege 999 is this: “we found a “problem” in your details”.
this is causing js errors.
You should not use regular expressions to escape your C# strings into a JavaScript friendly / safe format. Instead, assuming you are using .NET 4, you can use HttpUtility.JavaScriptStringEncode and it’s overload to take care of both single and double quotes for you.
For example:
Would ouput the following with
UserMsgset to “we found a “problem” in your details”: