C# 是否与 JavaScript 的 encodeURIComponent() 等效? [英] Does C# have an equivalent to JavaScript's encodeURIComponent()?
问题描述
在 JavaScript 中:
In JavaScript:
encodeURIComponent("©√") == "%C2%A9%E2%88%9A"
是否有 C# 应用程序的等效项?为了转义我使用的 HTML 字符:
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() + ";");
但我不确定如何将匹配转换为 JS 使用的正确十六进制格式.例如这段代码:
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])));
为 "©√"
返回 "%a9%221a"
而不是 "%C2%A9%E2%88%9A"
.看起来我需要将字符串拆分为字节或其他内容.
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.
这是一个 windows 应用程序,System.Web
中唯一可用的项目是:AspNetHostingPermission
、AspNetHostingPermissionAttribute
和 >AspNetHostingPermissionLevel
.
This is for a windows app, the only items available in System.Web
are: AspNetHostingPermission
, AspNetHostingPermissionAttribute
, and AspNetHostingPermissionLevel
.
推荐答案
Uri.EscapeDataString
或 HttpUtility.UrlEncode
是转义字符串的正确方法一个网址.
Uri.EscapeDataString
or HttpUtility.UrlEncode
is the correct way to escape a string meant to be part of a URL.
以字符串"Stack Overflow"
为例:
HttpUtility.UrlEncode("Stack Overflow")
-->"Stack+Overflow"
Uri.EscapeUriString("Stack Overflow")
--> "Stack%20Overflow"
Uri.EscapeDataString("Stack + Overflow")
--> 也将 "+" 编码为 "%2b"
---->Stack%20%2B%20%20Overflow
Uri.EscapeDataString("Stack + Overflow")
--> Also encodes "+" to "%2b"
---->Stack%20%2B%20%20Overflow
当用作 URL 的实际部分时,只有最后一个是正确的(而不是查询字符串参数之一的值)
Only the 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屋!