Convert Comma separated String to JavaScript String Array in C#

Last Reply 8 months ago By doctork11

Posted 8 months ago


I have ChartJS that needs an array with double quoted values.

// What I need is:

var jsVarMonths = ["January","February","March","April","May","June","July","August","September","October","November","December"];

// What I get is:

var jsVarMonths = ["January\",\"February\",\"March\",\"April\",\"May\",\"June\",\"July\",\"August\",\"September\",\"October\",\"November\",\"December"];

Here’s my code:

public List<string> GetMonths()
      var dq1 = @"""";
      var dq2 = @"""";
      var fdq = dq1 + "," + dq2;
      var s = Months;
      var replace = s.Replace(",", fdq);
      var myArray = new List<string> {replace};
      return myArray;
   catch (Exception e)
      Response.Write("<script>alert('" + Server.HtmlEncode(e.ToString()) + "')</script>");

I’ve been playing around a bit, so the code is a mess, but basically what I want is s.Replace(“,”, DOUBLE QUOTE + comma + DOUBLE QUOTE). For some reason, the debugger looks good, but the output keeps escaping with backslashes. Any thoughts on how to get rid of that backslash?

Maybe something I can do in the javascript? I tried to stringify and that didn’t work. 

var serializerMth = new JavaScriptSerializer();
var monthsDeclaration = string.Format("var jsVarMonths = {0};", serializerMth.Serialize(GetMonths()));
You are viewing reply posted by: doctork11 8 months ago.
Posted 8 months ago


Thank you for the code. I actually figured it out. I really just need to write out my problem, take a nap and look at it again. 

Here's what I did.

protected string[] MthArray { get; private set; }


var gs = new GetSiteStatsMaster();
MthArray = gs.MonthsCs.Split(",").ToCharArray();

Then from GetSiteStatsMaster()

var sdr = cmd.ExecuteReader();
while (sdr.Read())
    MonthsCs = sdr.GetString(0);
    ... etc...

the GetSiteStatsMaster returns a comma seperated value in a string.

I just put that string into a Char Array splitting on the comma.