之前為處理JavaScript字串的特殊字元寫過函數,今天發現.NET 4.0新增了HttpUtility.JavaScriptStringEncode,代表以後不用再自己土法鍊鋼DIY了,乖乖閃開,讓專業的來! (再一次,老鳥的身價持續走貶...)

順手測過效能:

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Web;
 
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string s = "I'm PC!\n\"I\tam\tPC!\"\n";
            Stopwatch sw = new Stopwatch();
            sw.Start();
            for (int i = 0; i < 3000000; i++)
            {
                string t = EscapeStringForJS(s);
            }
            sw.Stop();
            Console.WriteLine("EscapeStringForJS : {0}", EscapeStringForJS(s));
            Console.WriteLine("Duration {0}ms", sw.ElapsedMilliseconds);
 
            sw.Reset();
            sw.Start();
            for (int i = 0; i < 3000000; i++)
            {
                string u = HttpUtility.JavaScriptStringEncode(s);
            }
            sw.Stop();
            Console.WriteLine("JavaScriptStringEncode : {0}", 
                               HttpUtility.JavaScriptStringEncode(s));
            Console.WriteLine("Duration {0}ms", sw.ElapsedMilliseconds);
 
            Console.Read();
        }
 
        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(@"""", @"\""");
        }
 
    }
}

原廠出品,又比土砲函數更快,請安心使用~

EscapeStringForJS : I\'m PC!\n\"I\tam\tPC!\"\n
Duration 4427ms
JavaScriptStringEncode : I\u0027m PC!\n\"I\tam\tPC!\"\n
Duration 2275ms


Comments

Be the first to post a comment

Post a comment