Convert Comma separated String to JavaScript String Array in C#

Last Reply 5 months ago By doctork11

Posted 5 months ago

Hello,

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:

[WebMethod]
public List<string> GetMonths()
{
   try
   {
      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>");
      throw;
   }
}

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()));
Response.Write(monthsDeclaration);
Posted 5 months ago

Hi doctork11,

Check with the below code.

[WebMethod]
public List<string> GetMonths()
{
    var Months = "January,February,March,April,May,June,July,August,September,October,November,December";
    try
    {
        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>");
        throw;
    }
}

in Javascript replace with double quote.

var jsVarMonths = data.d[0].replace(/'/g, '"');

 


Posted 5 months ago

Hello,

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();
gs.GetData(id);
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.