views:

142

answers:

2

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  A: 

Replace any instance of " with &quot; as follows:

test.Replace( "\"", "&quot;" )
Nissan Fan
That still leaves it open for XSS attacks.
John Gietzen
I think you're incorrectly assuming that the string test is somehow coming in from the end user, which is not something that I see from the sample above. To me it's very clear that he controls the tooltips.
Nissan Fan
correct, security is not a concern.
fearofawhackplanet
+2  A: 

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 :)
John Gietzen