C#是否与JavaScript的encodeURIComponent()相当? [英] Does C# have an equivalent to JavaScript's encodeURIComponent()?
问题描述
在JavaScript中:
encodeURIComponent(©√)==%C2%A9%E2%88%9A
是否有C#应用程序的等效项?对于转义HTML字符,我使用:
txtOut.Text = Regex.Replace(txtIn.Text,@[\\\- \\\],
m => @&#+((int)m.Value [0])ToString()+;);
但我不知道如何将匹配转换为JS使用的正确的十六进制格式。例如这个代码:
txtOut.Text = Regex.Replace(txtIn.Text,@[\\\-\ uFFFF],
m => @%+ String.Format({0:x},((int)m.Value [0])));
返回%a9%221a
©√
而不是%C2%A9%E2%88%9A
。看起来我需要将字符串分割成字节或某些东西。
编辑:这是一个Windows应用程序,唯一可用的项目 ASP.NETHostingPermissionLevel
。
Uri.EscapeDataString
HttpUtility.UrlEncode
是逃避一个意图成为URL一部分的字符串的正确方法。
c code code code code > HttpUtility.UrlEncode(Stack Overflow) - > Stack + Overflow
Uri.EscapeUriString(Stack Overflow)
- > Stack%20Overflow
/ p>
Uri.EscapeDataString(Stack + Overflow)
- >还编码+到%2b
----> 堆栈%20%2B%20%20Overflow
O当用作URL的实际部分(与查询字符串参数之一的值相反)
时,nly
In JavaScript:
encodeURIComponent("©√") == "%C2%A9%E2%88%9A"
Is there an equivalent for C# applications? For escaping HTML characters I used:
txtOut.Text = Regex.Replace(txtIn.Text, @"[\u0080-\uFFFF]",
m => @"&#" + ((int)m.Value[0]).ToString() + ";");
But I'm not sure how to convert the match to the correct hexadecimal format that JS uses. For example this code:
txtOut.Text = Regex.Replace(txtIn.Text, @"[\u0080-\uFFFF]",
m => @"%" + String.Format("{0:x}", ((int)m.Value[0])));
Returns "%a9%221a"
for "©√"
instead of "%C2%A9%E2%88%9A"
. It looks like I need to split the string up into bytes or something.
Edit: This is for a windows app, the only items available in System.Web
are: AspNetHostingPermission
, AspNetHostingPermissionAttribute
, and AspNetHostingPermissionLevel
.
Uri.EscapeDataString
or HttpUtility.UrlEncode
is the correct way to escape a string meant to be part of a URL.
Take for example the string "Stack Overflow"
:
HttpUtility.UrlEncode("Stack Overflow")
-->"Stack+Overflow"
Uri.EscapeUriString("Stack Overflow")
-->"Stack%20Overflow"
Uri.EscapeDataString("Stack + Overflow")
--> Also encodes"+" to "%2b"
---->Stack%20%2B%20%20Overflow
Only the latter last is correct when used as an actual part of the URL (as opposed to the value of one of the query string parameters)
这篇关于C#是否与JavaScript的encodeURIComponent()相当?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!