Skip to content
Fix Code Error

Convert string with commas to array

March 13, 2021 by Code Error
Posted By: Anonymous

How can I convert a string to a JavaScript array?

Look at the code:

var string = "0,1";
var array = [string];
alert(array[0]);

In this case, alert would pop-up a 0,1. When it would be an array, it would pop-up a 0, and when alert(array[1]); is called, it should pop-up the 1.

Is there any chance to convert such string into a JavaScript array?

Solution

For simple array members like that, you can use JSON.parse.

var array = JSON.parse("[" + string + "]");

This gives you an Array of numbers.

[0, 1]

If you use .split(), you’ll end up with an Array of strings.

["0", "1"]

Just be aware that JSON.parse will limit you to the supported data types. If you need values like undefined or functions, you’d need to use eval(), or a JavaScript parser.


If you want to use .split(), but you also want an Array of Numbers, you could use Array.prototype.map, though you’d need to shim it for IE8 and lower or just write a traditional loop.

var array = string.split(",").map(Number);
Answered By: Anonymous

Related Articles

  • What are access specifiers? Should I inherit with private,…
  • Regular expression to match numbers with or without commas…
  • polymer 1.0 event firing among nested components
  • How to avoid a System.Runtime.InteropServices.COMException?
  • Using SELECT result in another SELECT
  • How to get dynamic column data linq
  • How do I include certain conditions in SQL Count
  • vue unexpected reactivity from props
  • How can I parse a CSV string with JavaScript, which contains…
  • Finding all possible combinations of numbers to reach a…

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

Change the maximum upload file size

Next Post:

What does a “Cannot find symbol” or “Cannot resolve symbol” error mean?

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

  • Get code errors & solutions at akashmittal.com
© 2022 Fix Code Error