Showing posts with label escape. Show all posts
Showing posts with label escape. Show all posts

Wednesday, March 28, 2012

String.Formatting a javascript code sample, how do I escape the { } characters?

Hi,

I'm trying to String.format a piece of javascript code

string.Format("function showalert(msg) { window.status = '{0}'; alert(msg); }", "Test");

This compiles ok but when it runs it has a Input string was not in a correct format exception as the '{' and '}' characters are reserved and used for substitution in the string.Format function.

Is there a way I can escape the '{}' characters so that the string.format function ignores them?

I've tried

string.Format("function showalert(msg) \{ window.status = '{0}'; alert(msg); \}", "Test");

which is normally how you escape but it dosen't work.

Thanks for your help

Auschucky

Hi ,To specify a single literal brace character informat, specify two leading or trailing brace characters; that is, "{{" or "}}".
string test =string.Format("function showalert(msg) {{ window.status = '{0}'; alert(msg); }}","Test");
Hope this helps , Gook Luck^_^
Ta, worked a treat

Monday, March 26, 2012

stringbuilder & javascript (escape characters for quotes?)

Hey,

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,

StringBuilder with line break escape.

I created a StringBuilder and append string values to it, but each string I inserted a "\n" to sparate values. When I write the StringBuilder values out to a text file. The line break with "\n" did not work. Anybody knows why?

StringBuilder sb = new StringBuilder();
sb.Append("Some Value \n");
sb.Append("Another Value \n");

// create a stream writer and write all string values to the file
StreamWriter sw = File.CreateText(path)
sw.WriteLine(sb.ToString());

Another question, what is the default Capacity of a StringBuilder object created like the code above?\n is a javascript newline but you are not using javascript...instead do something like this:


StringBuilder sb = new StringBuilder();
sb.Append("Some Value" & vbcrlf);
sb.Append("Another Value" & vbcrlf);

'or

StringBuilder sb = new StringBuilder();
sb.Append("Some Value" & vbnewline);
sb.Append("Another Value" & vbnewline);


oooh, just realized that this is c#....I know the vbnewline and vbcrlf do new lines in VB but not sure about c#...sorry

Also, to your other question...from the online notes for stringbuilder:
----------------------
Notes to Implementers: The default capacity for this implementation is 16, and the default maximum capacity is Int32.MaxValue.
----------------------

MajorCats
All .net languages support the Environment.NewLine property. The property value is a constant customized specifically for the current platform. This value is automatically appended to text when using WriteLine methods.

Try that instead.

However, couldn't you simply rewrite the entire chunk as:


StreamWriter sw = File.CreateText(path)
sw.WriteLine("Some Value");
sw.WriteLine("Another Value");
...and avoid the StringBuilder entirely (since the WriteLine method will automatically insert on a newline?

Not sure about the Capacity question. From MSDN:

Capacity does not affect the string value of the current instance. Capacity can be decreased as long as it is not less than Length.

The StringBuilder dynamically allocates more space when required and increases Capacity accordingly. For performance reasons, a StringBuilder might allocate more memory than needed. The amount of memory allocated is implementation-specific.
First of al it is better to use Environment.NewLine.
But if you realy want to use it, use \r\n ... that will work
Cool, thank you all.

Environment.NewLine works perfectly in my situation, "\r\n" works as well in C#.
In addition to daver's post:

The StringBuilder allows for specifying the capacity by using the Capacity property:
sb.Capacity = 200 allows for 200 characters. The default capacity is 16.

so don't think that you should never use StringBuilder. The StringBuilder should be used in place of concatenating strings instead of using the &= as that creates a new instance of the string each time it is used and should provide better performance with large strings.
I use StringBuilder just for the performance reason you mentioned. But, I don't believe its default capacity is 16, as it's too small. The first replier said it is the maximum value of int. This sounds reasonable to me. Are you saying that it initially allocate a buffer for 16 characters, and will auto-expand the buffer as needed? The fininal buffer size would not exceed StringBuilder's default capacity. Is this right?
The default capacity for this implementation is 16, and the default maximum capacity is Int32.MaxValue (2,147,483,647; that is, hexadecimal 0x7FFFFFFF)
Hi, adec

What do you mean by "this implementation"? When I create a StringBuilder object by:

StringBuilder sb = new StringBuilder();

What does the "16" mean to me? I should not worry about anything as long as total number of char in my final string is less than Int32.MaxValue, shouldn't I?
You do not really have to worry about it. If you are pretty sure to what capacity your SB should cater, set it to limit the memory allocated. If you don't, the SB will automatically adapt. In fact you may well set it to 16 (characters) in the first place. It will dynamically adapt.
I've never done the performance comparison,
but rather than concatenate the newline (we're avoiding concatenation - right?)

try using the stringbuilder.appendformat method

sb.AppendFormat("Some Value{0}", Environment.NewLine);
sb.Appendformat("Another Value{0}", Environment.NewLine);
As a general rule, if you need to create a lot of text, do not use Concatenation. Performance wise, the Stringbuilder is superior to Concatenation, and should be used in place of this.
try this:


StringBuilder s = new StringBuilder();
s.Append("HEllo <BR>");
s.Append("World");
Response.Write(s);

I am actually kind of curious as to why one would instantiate a StringBuilder (using line terminations), use the File.CreateText to create a StreamWriter, and then call StreamWriter.Write() passing the StringBuilder to the StreamWriter when the StreamWriter does it all?
StreamWriter sw = new StreamWriter(@."path");
sw.WriteLine("SomeValue");
sw.WriteLine("AnotherValue");
sw.Close();

Is there anything wrong with this approach?
I suppose that all depends on what you need the string for.

if you need it for multiple purposes, then creating a stringbuilder is ok as its reusable.
if you need to perform replacements then appendformat is very useful.
if you have additional concatenations to perform then stringbuilder is best.
i.e. dont do (sw.WriteLine("SomeValue" & "somother value" & "yet anothervalue");

if you're just blasting data into a disk file, then perhaps a stringbuilder represents an extra [unnecessary] step.

of course, we're all just speculating about the real world requirement behind the original posters question...