class TestEscapeJSString
{
/// <summary>
/// Replace characters for Javscript string literals
/// </summary>
/// <param name="text">raw string</param>
/// <returns>escaped string</returns>
public static string EscapeStringForJS(string s)
{
//REF: http://www.javascriptkit.com/jsref/escapesequence.shtml
return s.Replace(@"\", @"\\")
.Replace("\b", @"\b")
.Replace("\f", @"\f")
.Replace("\n", @"\n")
.Replace("\0", @"\0")
.Replace("\r", @"\r")
.Replace("\t", @"\t")
.Replace("\v", @"\v")
.Replace("'", @"\'")
.Replace(@"""", @"\""");
}
public static void Test()
{
Stopwatch sw = new Stopwatch();
sw.Start();
string s = "I'm PC!\n\"I\tam\tPC!\"\n";
for (int i = 0; i < 3000000; i++)
{
string t = EscapeStringForJS(s);
}
sw.Stop();
Console.WriteLine("Duration {0}ms", sw.ElapsedMilliseconds);
}
//Method 2,
//Using Dictionary to store the escape characters mapping
//But it's slower than hard-coding style
//3,000,000 times: 6,145ms vs 8,181ms
static Dictionary<string, string> escMap =
new Dictionary<string, string>()
{
{"\b", @"\b"}, {"\f", @"\f"}, {"\n", @"\n"},
{"\0", @"\0"}, {"\r", @"\r"}, {"\t", @"\t"},
{"\v", @"\v"}, {"'", @"\'"}, {@"""", @"\"""}
};
public static string EscapeStringForJSX(string s)
{
s = s.Replace(@"\", @"\\");
foreach (string k in escMap.Keys)
s = s.Replace(k, escMap[k]);
return s;
}
}