Im trying to write a javascript array from .net. The values of the array will sometimes have single quotes in - therefore I need some way to process the quotes so that I can output the javascript in the correct way.
I have:
sb.Append("templateDetails["+ i +"] = new Array('"+ dr[0].ToString() +"','"+ dr[1].ToString()+"','"+ dr[2].ToString() +"');\n");
However, this does not deal with the quotes. I tried:
sb.Append("templateDetails["+ i +"] = new Array('"+ dr[0].ToString().Replace("'","\'") +"','"+ dr[1].ToString().Replace("'","\'") +"','"+ dr[2].ToString().Replace("'","\'") +"');\n");
This was to try and replace all single quotes with \' which is the javascript escape character.
However, the double quotes dont work because .net think I'm adding more code.
kind of like in original asp when you have to have multiple quotes to get in a single quote...you know what I mean :)
any help much appreciated,
PeteThe first code sample should do fine.. single quote isnt going to trip anything up. If you were wanting to use double quotes in your string-builder for javascript, you would have to escape them with \" .
Now, are you anticipating a single quote will be in your datareader columns that you are building the stringbuilder with? If so, replacethose values with \' instead of the whole stringbuilder.
Cheers Sharbel,
Trying that today.
Pete
Hold on :)
I am anticipating single quotes in the data columns. Example: " today it's the first day ... " etc etc.
I've tried putting the dataReader columns into strings then replacing single quotes with \' but that doesnt seem to work...
Pete
Hey,
completely by chance I found that backslash is an escape character for .net as well as javascript:
hence:
dr[4].ToString().Replace("'","\\'")
works fine
Cheers,
Pete
Hi Pete,
FYI, the slash isn't a ".NET" escape character, per se; it works in C# because C# shares a lot of common syntax with Javascript (and Java, and C++, and any other languages that descended from C in one form or another).
In VB.NET, you escape double quotes by repeating them, just like in old "Classic" ASP with VBScript (although if you used JScript for Classic ASP, you *would* need to use the slash to escape characters).
Cheers,
0 comments:
Post a Comment