3

Is there a way for the format string used in a call to string.format to contain a { character that is not used for substring insertion?

For example how could I do this...

string.format("my format has this { in it {0}", abc);

returning...

"my format has this { in it abc"

I need to do this as the string I am creating in HTML and will contan a script block of javascript.

Thank you

Etienne de Martel
  • 34,692
  • 8
  • 91
  • 111
Ben Cameron
  • 4,335
  • 6
  • 51
  • 77
  • possible duplicate of [Output '{' or '}' with string.format(...)](http://stackoverflow.com/questions/2361742/output-or-with-string-format) – Conrad Frix Dec 06 '11 at 15:37
  • 1
    It should be noted that there's an entire section on this in the documentation: http://msdn.microsoft.com/en-us/library/txafckwd.aspx – phoog Dec 06 '11 at 15:38

5 Answers5

14

Yup, you just need to double it:

string.Format("my format has this {{ in it {0}", abc);

See the "escaping braces" section on the MSDN page for Composite Formatting for more details.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
4

Double it up to escape it. So "{{" will work properly and will output from the string.format as a single "{"

Tarwn
  • 1,030
  • 8
  • 7
4

Use double {{ brace in your format string.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
2

Here's an article that explains how to escape the curly brace in string.format with a few examples and some good reading.

http://msdn.microsoft.com/en-us/netframework/aa569608#Question2

EDIT: Adding useful text to accompany link :)

user1231231412
  • 1,659
  • 2
  • 26
  • 42
-2

it is called escaping. mostly you do a \ in front of the odd char

nico
  • 1,039
  • 4
  • 13
  • 27