Quantcast
Channel: General .NET – Brian Pedersen's Sitecore and .NET Blog
Viewing all articles
Browse latest Browse all 167

Javascript string encoding in C#

$
0
0

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.



Viewing all articles
Browse latest Browse all 167

Trending Articles