0
<document.write("<SCR"+"IPT TYPE='text/javascript' SRC='"+"http"+(window.location.protocol.indexOf('https:')==0?'s':'')+"://"+gDomain+"/"+gDcsId+"/wtid.js"+"'><\/SCR"+"IPT>");

我需要转义上面的字符串才能将整个内容添加到 StringBuilder 但到目前为止我必须遗漏一些东西,因为字符串终止不正确......

4

4 回答 4

7

你应该尝试这样的事情:

@"<document.write(""<SCR""+""IPT TYPE='text/javascript' SRC='""+""http""+(window.location.protocol.indexOf('https:')==0?'s':'')+""://""+gDomain+""/""+gDcsId+""/wtid.js""+""'><\/SCR""+""IPT>"");"

当使用 @ 为字符串文字添加前缀时,唯一需要的转义是将 " 字符加倍。

希望这有帮助。

于 2008-12-04T10:31:04.863 回答
4
string x = @"<document.write(""<SCR""+""IPT TYPE=""'text/javascript' SRC='""+""http""+(window.location.protocol.indexOf('https:')==0?'s':'')+""://""+gDomain+""/""+gDcsId+""/wtid.js""+""'><\/SCR""+""IPT>"");";

@ 前缀使转义更简单。你只需要把每个“变成”。

如果您将 JavaScript 存储在外部文件中,您会发现您的程序更易于维护。我假设您正在使用 StringBuilder 以便您可以将一些常量脚本与一些动态值混合在一起?您可以将它写在一个文件中,但将这样的转义符用于动态值:

var fromCSharp = {0};

Then at runtime, load the JS file and give it to string.Format as the format string, along with values to replace each occurrence of {0}, {1}, etc. You only need to load the format string from the file once and keep it cached.

Also if the values you are inserting into the JavaScript are themselves string literals, you will need to escape them according to the syntax of JavaScript.

于 2008-12-04T10:32:35.360 回答
0

我认为您正在混淆什么是JavaScript和什么是C#。你能告诉我们你想要实现的字符串吗?

例如

window.location.protocol.indexOf('https:')JavaScript

但大概

gDomaingDcsId

是您C#方法中的变量

也许是这样:

"<SCRIPT TYPE='text/javascript' SRC='"+"http"+"(window.location.protocol.indexOf('https:')==0?'s':'')"+"://" + gDomain + "/"+ gDcsId+ "/wtid.js"+"'></SCRIPT>")
于 2008-12-04T10:22:53.400 回答
0

开头的字符串正是我想要的......(我没有将 JavaScript 与 C# 混合 - 我只需要在 C# StringBuilder 中添加一个字符串,巧合包含一些 JavaScript)

它是我必须使用 StringBuilder 放在页面上的外部脚本(出于各种原因)。

我无法知道对脚本的任何更改是否会使其失败,所以我必须按原样包含它......

它只是整个脚本的 1 行,但我设法正确地逃脱了大多数其他行,并且它们被包含在内...

于 2008-12-04T10:28:13.903 回答