noesgard
noesgard

Reputation: 6139

C# StringBuilder - how to escape this string:

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

I need to escape the string above in order to add the whole thing to a StringBuilder but so far I must be missing something because string termination is not correct...

Upvotes: 0

Views: 9937

Answers (4)

Daniel Earwicker
Daniel Earwicker

Reputation: 116674

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

The @ prefix makes escaping simpler. You just have to turn each " into "".

You will find your program much easier to maintain if you store the JavaScript in an external file. I assume you're using StringBuilder so you can mix bits of constant script with a few dynamic values? You could write it in a file but put escapes like this for the dynamic values:

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.

Upvotes: 4

Stephane
Stephane

Reputation: 151

You should try something like this :

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

When prefixing a string literal with @, the only escaping needed is to double the " caracter.

Hope this help.

Upvotes: 7

Ian G
Ian G

Reputation: 30234

I think you are mixing up what is JavaScript and what is C#. Can you please tell us the string you are string you are trying to achieve...

for instance

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

but presumably

gDomain and gDcsId

are variables from your C# method

maybe this:

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

Upvotes: 0

noesgard
noesgard

Reputation: 6139

The string in the beginning is what I want exactly... (I'm not mixing up JavaScript with C# - I just need to add a string to at C# StringBuilder that by coincidance contains some JavaScript)

Its an external script that I have to put on a page, using a StringBuilder (for various reasons).

I have no way of knowing if any changes to the script will make it fail so I have to include it as is...

It's only 1 line of the total script, but most other lines I've managed to escape correctly and they are included as wanted...

Upvotes: 0

Related Questions