Amund
Amund

Reputation: 41

JavaScript Array to String

I'm using the jQuery plugin jQuery-Tokenizing-Autocomplete in a rails application with a has_many association.

I need to save the values to the database, but to do that I need it to be a string, not an array. So the result should equal "1","2","3". Hope this clarifies.

The javascript used to generate this array:

$.TokenList.ParseValue = function (value, settings) {
  var result = [];
  $.each(value, function(i, node) {
    if (node) {
      result.push(node.id);
    }
  });
  return result;  
};

Upvotes: 1

Views: 812

Answers (3)

Aj Banda
Aj Banda

Reputation: 23

for array to string in javascript you can do it like this.

var str = (['1', '2', '3']).join(","); // will result to 1,2,3

similar syntax works for ruby code

['1', '2', '3']).join(",") # will return 1,2,3

Upvotes: 1

Casey Chu
Casey Chu

Reputation: 25463

var string = '"' + array.join('","') + '"'; // "1","2","3"

Upvotes: 0

Fred
Fred

Reputation: 8602

The default separator for join is the comma, so remove the '","' argument. You are specifying a separator of "," so the double quotes must be escaped in the result string, hence the backslashes.

Upvotes: 0

Related Questions