问题
i am using a 3rd party library to show tooltips, like so:
string tooltip = "test";
output.Write("onmouseover='Tip(\"" + test + "\");'"); // work fine :)
i'm having problem with situations like the following where i need quotes for formatting:
string tooltip = "<span style='color:red;'>test</span>";
output.Write("onmouseover='Tip(\"" + test + "\");'"); // no working :(
how can i escape the quotes needed for the html in the tooltip so it doesn't break the function call?
回答1:
Replace any instance of "
with "
as follows:
test.Replace( "\"", """ )
回答2:
This is the perfect use for the Microsoft Anti-Xss Library
With it, you call the JavaScriptEncode function, which will build a string like this:
Microsoft.Security.Application.AntiXss.JavaScriptEncode("ab'c\"d")
// 'ab\x27c\x22d'
Notice that it includes the quotes.
You would take that, HTML encode it, and plop it directly into your parenthesis.
Something like this:
string tooltip = "<span style='color:red;'>test</span>";
output.Write("onmouseover=\"Tip(" + AntiXss.JavaScriptEncode(test) + ");\""); // working :)
来源:https://stackoverflow.com/questions/2223543/dealing-with-nested-quotes-in-html-generated-from-c-sharp