I’m surprised that I’ve never needed this before, but today I wanted to embed some JavaScript within a string contained in a C# class and format it using string.Format(...).

The problem? My JavaScript was a function declaration and therefore contained braces, but the placeholder delimiters in string.Format(...) also use braces.

The solution: braces get escaped using another brace of the same type.

var jsConditionalHelloWorldTemplate =
    "if ({0}) {{" + Environment.NewLine +
    "    alert('Hello, world!');" + Environment.NewLine +
    "}}" + Environment.NewLine +
    "";

var sendToBrowser = string.Format(jsConditionalHelloWorldTemplate, "true"); 
writer.Write(sendToBrowser);