netchi
netchi

Reputation: 67

change string to double quotes

I have a collection of strings. I am trying to convert it to an array. The

   var company = "Toyota,Honda,Ford";
   var array = '[' + company.split( "," ).join( '"','"' ) + ']';  \\prints out "["Toyota"Honda"Ford"]" . It should be ["Toyota","Honda","Ford"]
   console.log(array);

array[0] should be Toyota and so on. What am I missing?

Upvotes: 0

Views: 35

Answers (2)

Red
Red

Reputation: 7299

Just use company.split( "," ). You are joining them using .join(...) which converts it back to a string.

split() already creates an array.

var company = "Toyota,Honda,Ford";
var array = company.split( "," );
   console.log(array);

Upvotes: 2

mwilson
mwilson

Reputation: 12910

You can accomplish it a little more simplified by splitting, then maping your quotes in there. I think your main problem is you're trying to do array operations and string operations. You shouldn't need to do any string operations other than your request to wrap your items in double-quotes. Other than that, you already split your string into an array since you have a , as a delimiter. So, simply make it an array, then wrap your elements with double-quotes.

Example:

var company = "Toyota,Honda,Ford";
var array = company.split(',').map(c => `"${c}"`);
console.log(array[0]);

Upvotes: 1

Related Questions