注意将C#字符串编码为Javascript字符串 [英] Caveats Encoding a C# string to a Javascript string

查看:181
本文介绍了注意将C#字符串编码为Javascript字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个自定义的JavaScript MVC3 Helper类对我的项目,其中一个方法应该是将C#字符串转义为Javascript字符串。

I'm trying to write a custom Javascript MVC3 Helper class foe my project, and one of the methods is supposed to escape C# strings to Javascript strings.

我知道C#字符串是 UTF-16编码的,以及Javascript字符串也似乎是UTF-16

I know C# strings are UTF-16 encoded, and Javascript strings also seem to be UTF-16. No problem here.

我知道一些角色,如反斜杠,单引号或双引号必须在JavaScript上进行反斜杠转义,所以:

I know some characters like backslash, single quotes or double quotes must be backslash-escaped on Javascript so:

\ becomes \\
' becomes \'
" becomes \"

在写我的转换方法之前,还有其他注意事项吗?

Is there any other caveat I must be aware of before writing my conversion method ?

编辑:
到目前为止,很好的答案,我从未来的答案中增加一些参考资料。

Great answers so far, I'm adding some references from the answers in the question to help others in the future.

Alex K.建议使用 System.Web.HttpUtility.JavaScriptStringEncode ,我标记为正确因为我正在使用.Net 4.但是这个功能不能用于以前的.Net版本,所以我在这里添加一些其他资源:

Alex K. suggested using System.Web.HttpUtility.JavaScriptStringEncode, which I marked as the right answer for me, because I'm using .Net 4. But this function is not available to previous .Net versions, so I'm adding some other resources here:

CR  becomes \r   // Javascript string cannot be broke into more than 1 line
LF  becomes \n   // Javascript string cannot be broke into more than 1 line
TAB becomes \t

Control characters must be Hex-Escaped

JP Richardson 给了一个有趣的链接,通知Javascript使用UCS-2,这是UTF-16的一个子集,但如何正确编码这是一个全新的问题。

JP Richardson gave an interesting link informing that Javascript uses UCS-2, which is a subset of UTF-16, but how to encode this correctly is an entirely new question.

LukeH对以下注释提醒了CR,LF和TAB字符,并提醒我控制字符(BEEP,NULL,ACK等)。

LukeH on the comments below reminded the CR, LF and TAB chars, and that reminded me of the control chars (BEEP, NULL, ACK, etc...).

推荐答案

)你可以;

System.Web.HttpUtility.JavaScriptStringEncode(@"aa\bb ""cc"" dd\tee", true);
== 
"aa\\bb \"cc\" dd\\tee"

这篇关于注意将C#字符串编码为Javascript字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆