Search code examples
c#stringjoinbackslashsingle-quotes

Get backslash in string with a string join


I have the following code which must replace a ' with a \' in a string (which I need to use in javascript later on). I do not seem to be able to get the backslash in the word. Input: "Aujourd'hui"; Output wanted "Aujourd\'hui" (multiple single quotes in the input string may occur).

  char[] separators = new char[] { '\u0027' };

  string s = "Aujourd'hui";
  string[] temp = s.Split(separators, StringSplitOptions.RemoveEmptyEntries);
  s = string.Join(@"\\'", temp);

  return (s);

What do I do wrong?


Solution

  • Remove one of your backslashes to produce the literal text: \'

    This code:

      s = string.Join(@"\\'", temp);
    

    should be changed to:

      s = string.Join(@"\'", temp);