3

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.

1
  • 1
    You can iterate over the values and process them accordingly... but I see your point. It would have helped if you posted what you have tried so far an explicitly pointed out what you have problems with. If you just ask how to convert this comma separated string into this array, then this is something which already has been discussed before. The more information you provide and the more effort you put into your question, the more effort we put into answers. Commented Aug 9, 2012 at 12:31

3 Answers 3

3

Try:

var initialString = "'California',51.2154,-95.2135464,'data'";
var dataArray = initialString .split(",");
Sign up to request clarification or add additional context in comments.

1 Comment

dataArray from this answer is not the same as data from the question.
2

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.

5 Comments

It will become like ["'California'","51.2154","-95.2135464","'data'"] It's wrong
Do not edit out the possible duplicate banner like you did on this question - stackoverflow.com/q/11883187/50776 - Doing so in the future may result in further moderator action.
@casperOne I'll be aware of that in the future though I think your rollback was unnecessary.
@Christoph No, it was absolutely necessary, as you defaced a system-generated banner. Those are off limits. There is never a reason to edit it out if the question is closed as a duplicate. Just because you don't think it's a duplicate doesn't mean you can edit it out.
Though I understand your argument, and I will not do that again I see no sense in doing a rollback and then removing the message in another separate edit removing the clarification that was necessary so that people don't close it as duplicate yet again (like they erroneously did in the first place...).
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.