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

0 comments:

Post a Comment