Home > Back-end >  c# appendformat changes value for backslash
c# appendformat changes value for backslash

Time:07-22

i am creating a jquery script in c# to populate on the page. One of my field id's has a period, so i need to place a \ before the period so the jquery will work. When i use the appendformat it removes one of the backslash:

s.AppendFormat("\t\t\t\t $(\'#{0}\').show();", "test\\.test");

expected result:

$('#test\\.test').show();

CodePudding user response:

There are two levels of escaping to consider. The first is C# literals (which is what's causing \t to produce a tab character), and the second is JavaScript. Both languages escape the backslash with a preceding backslash, so to end up with two backslashes in your JavaScript you need to have four backslashes in your C# string:

"test\\\\.test"

Or, alternatively, use a verbatim string, which doesn't use backslashes for escape characters:

@"test\\.test"
  • Related