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.
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.
Share Improve this question asked Aug 4, 2009 at 5:26 leoraleora 197k367 gold badges906 silver badges1.4k bronze badges5 Answers
Reset to default 10You'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)
html = html.Replace("'", "%27");
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.
I found that the AntiXSS library was not able to accomplish what I was looking for, which was to encode server side and decode in javascript.
Instead I used Microsoft.JScript.dll which allows you to:
GlobalObject.escape(string);
and on the client side in javascript:
unescape(string);
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(@"""", @"\""");