keyur ajmera
keyur ajmera

Reputation: 63

Convert comma separated string to a JavaScript array

I have this string:

"'California',51.2154,-95.2135464,'data'" 

I want to convert it into a JavaScript array like this:

var data = ['California',51.2154,-95.2135464,'data'];

How do I do this?

I don't have jQuery. And I don't want to use jQuery.

Upvotes: 3

Views: 25701

Answers (3)

Christoph
Christoph

Reputation: 51211

Use the split function which is available for strings and convert the numbers to actual numbers, not strings.

var ar = "'California',51.2154,-95.2135464,'data'".split(",");

for (var i = ar.length; i--;) {
  var tmp = parseFloat(ar[i]);
  ar[i] = (!isNaN(tmp)) ? tmp : ar[i].replace(/['"]/g, "");
}

console.log(ar)

Beware, this will fail if your string contains arrays/objects.

Upvotes: 2

HBP
HBP

Reputation: 16033

Since you format almost conforms to JSON syntax you could do the following :

var dataArray = JSON.parse ('[' + initialString.replace (/'/g, '"') + ']');

That is add '[' and ']' characters to be beginning and end and replace all "'' characters with '"'. than perform a JSON parse.

Upvotes: 1

George D
George D

Reputation: 2365

Try:

var initialString = "'California',51.2154,-95.2135464,'data'";
var dataArray = initialString .split(",");

Upvotes: 3

Related Questions