Javascript string encoding in C#

In a previous post I explained how you can use the C# System.Uri.EscapeDataString() to encode strings to be later decoded by the equvivalent JavaScript decodeURIComponent().

The method above is still valid when encoding HTML tags, but fails short when encoding quotations and ampersands.

The following string in C# will fail when rendered as JavaScript:

string s = "hello's are better than goodbye's";
Response.Write("<script language='javascript'>alert('" + s + "');</script>");

We need to encode the ampersands (the ‘). This will produce a correct output:

string s = @"hello\'s are better than goodbye\'s";
Response.Write("<script language='javascript'>alert('" + s + "');</script>");

The \ will escape the ‘ signs.

Now, .NET 4.0 have introduced a function, HttpUtility.JavaScriptStringEncode() method. This function escapes quotes and double quotes as well as ?’s and &’s.

For us who does not have the possibility to use .NET 4.0, the function is pretty easy to develop. And why not pair it with the System.Uri.EscapeDataString() so you get a complete clean string encoding.

This Extension Method will escape the data and all quotes in one go:

public static class StringExtensions
  public static string ToJavaScriptString(this String instr)
    return Uri.EscapeDataString(instr).Replace("'", @"\'").Replace(@"""", @"\""");

To use the function you can do the following:

string s = "<h1>hello's</h1>";
Response.Write("<script language='javascript'>alert(decodeURIComponent('" + s.ToJavaScriptString() "'));</script>");

Now you will never have any problems with HTML tags, quotes, double quotes, ampersands or other special signs.

About briancaos

Developer at Pentia A/S since 2003. Have developed Web Applications using Sitecore Since Sitecore 4.1.
This entry was posted in .net, c#, General .NET and tagged , , , . Bookmark the permalink.

4 Responses to Javascript string encoding in C#

  1. Joe Enos says:

    I was working with this recently, and JavaScriptStringEncode does not escape question marks or ampersands – only quotes, whitespace, backslashes, and angle brackets (though I’m not sure why they do angle brackets). The MSDN documentation is a little weird here – I think there’s either a mistake or it’s just very unclear.

  2. Thank you so much for this I was really battling to get this working!!!

  3. Jeow Li Huan says:

    It encodes angle brackets so that when embedding JavaScript inside HTML,
    var abc = ”
    won’t be recognized as a end script tag.

  4. Lisa Y. says:

    Thanks, this was a lifesaver! .Net could really use 4-level escaping for certain situations.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s