Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does String.Format convert a forward slash into a minus sign?

Why does String.Format("/") get converted to "-"?

like image 673
Jacko Avatar asked Aug 09 '11 16:08

Jacko


People also ask

How do you remove a forward slash from a string?

To replace all forward slashes in a string: Call the replace() method, passing it a regular expression that matches all forward slashes as the first parameter and the replacement string as the second. The replace method will return a new string with all forward slashes replaced.

How do you make a string backslash?

If you want to include a backslash character itself, you need two backslashes or use the @ verbatim string: var s = "\\Tasks"; // or var s = @"\Tasks"; Read the MSDN documentation/C# Specification which discusses the characters that are escaped using the backslash character and the use of the verbatim string literal.

How do you escape a forward slash in Javascript?

We should double for a backslash escape a forward slash / in a regular expression. A backslash \ is used to denote character classes, e.g. \d . So it's a special character in regular expression (just like in regular strings).


2 Answers

I suspect that you are using the / symbol inside a {0} placeholder. It is a reserved symbol used as datetime separator in the given culture. You could escape it, like this:

string date = string.Format("{0:dd\\/MM\\/yyyy}", DateTime.Now);
like image 92
Darin Dimitrov Avatar answered Sep 26 '22 07:09

Darin Dimitrov


As per Custom Date and Time Format Strings, / refers to the culture's date separator. So you need to escape it. You can either use a backslash as per Darin's answer, or you can quote it in single quotes. For example:

using System;
using System.Globalization;

class Test
{
    static void Main()
    {
        DateTime date = DateTime.Now;

        CultureInfo da = new CultureInfo("da");
        // Prints 09-08-2011
        Console.WriteLine(string.Format(da, "{0:dd/MM/yyyy}", date));
        // Prints 09/08/2011
        Console.WriteLine(string.Format(da, "{0:dd'/'MM'/'yyyy}", date));
        // Prints 09/08/2011
        Console.WriteLine(string.Format(da, "{0:dd\\/MM\\/yyyy}", date));
    }
}
like image 25
Jon Skeet Avatar answered Sep 24 '22 07:09

Jon Skeet