C# alternative for javascript escape function

匿名 (未验证) 提交于 2019-12-03 02:20:02

问题:

what is an alternative for javascript escape function in c# for e.g suppose a string:"Hi Foster's i'm missing /you" will give "Hi%20Foster%27s%20i%27m%20missing%20/you" if we use javascript escape function, but what is the alternative for c#. i have searched for it but no use.

回答1:

You can use:

string encoded = HttpUtility.JavaScriptStringEncode(str);

Note: You need at least ASP.NET 4.0 to run the above code.



回答2:

The best solution I've seen is mentioned on this blog - C#: Equivalent of JavaScript escape function by Kaushik Chakraborti. There is more to escaping javascript than simply url-encoding or replacing spaces with entities.



回答3:

var unescapedString = Microsoft.JScript.GlobalObject.unescape(yourEscapedString);  var escapedString = Microsoft.JScript.GlobalObject.escape(yourUnescapedString);


回答4:

Following is the escape function implementation that you will find in Microsoft.JScript.dll...

[NotRecommended("escape"), JSFunction(JSFunctionAttributeEnum.None, JSBuiltin.Global_escape)] public static string escape(string str) {     string str2 = "0123456789ABCDEF";     int length = str.Length;     StringBuilder builder = new StringBuilder(length * 2);     int num3 = -1;     while (++num3 < length)     {         char ch = str[num3];         int num2 = ch;         if ((((0x41 > num2) || (num2 > 90)) &&              ((0x61 > num2) || (num2 > 0x7a))) &&              ((0x30 > num2) || (num2 > 0x39)))         {             switch (ch)             {                 case '@':                 case '*':                 case '_':                 case '+':                 case '-':                 case '.':                 case '/':                     goto Label_0125;             }             builder.Append('%');             if (num2 < 0x100)             {                 builder.Append(str2[num2 / 0x10]);                 ch = str2[num2 % 0x10];             }             else             {                 builder.Append('u');                 builder.Append(str2[(num2 >> 12) % 0x10]);                 builder.Append(str2[(num2 >> 8) % 0x10]);                 builder.Append(str2[(num2 >> 4) % 0x10]);                 ch = str2[num2 % 0x10];             }         }     Label_0125:         builder.Append(ch);     }     return builder.ToString(); }

Code taken from Reflector.



回答5:

The best solution I've seen is mentioned on this blog - C#: Equivalent of JavaScript escape function by Kaushik Chakraborti. There is more to escaping javascript than simply url-encoding or replacing spaces with entities.

I noticed another solution in the comments in KodeSharp article that may be better. The comment says it is more compatible with UTF-8 and does not require the reference to JScript. Is this better?

(Dependent on System.Web.Extensions.dll)

using System.Web.Script.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!