views:

434

answers:

3

i am building up a string on the server that is getting put into a javascript variable on the client.

what is the best of encoding this to avoid any issues

right now on the server i am doing something like this:

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

but i assume there is a more elegant fool proof way of doing stuff like this.

+5  A: 

You're really better off using the Microsoft Anti-Cross Site Scripting Library to do this. They provide a JavaScriptEncode method that does what you want:

Microsoft.Security.Application.AntiXss.JavaScriptEncode("My 'Quotes' and ""more"".", False)
Nicholas H
A: 

I'm not sure in which context you're using this string, but \' might be what you're looking for. The backslash is an escape character and allows you to use certain characters that can't otherwise be present in a string literal. This is what the output JavaScript should look like:

alert('It\'s amazing');

Of course, you could use alert("It's amazing"); in this particular case.

Anyway, if you're building JavaScript code:

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

On the other hand, there are other characters besides apostrophes that need some processing. Using the Microsoft Anti-Cross Site Scripting Library would get all of them at once.

Thorarin
A: 

The characters that you need to escape in a string value are the backslash and the character used as string delimiter.

If apostrophes (') are used as string delimiter:

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

If quotation marks (") are used as string delimiter:

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

If you don't know which delimiter is used, or if it may change in the future, you can just escape both:

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