Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string with commas to array

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 shows 0,1. If it where an array, it would show 0. And if alert(array[1]) is called, it should pop-up 1

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

like image 670
Scott Avatar asked Nov 07 '12 15:11

Scott


People also ask

How do I change a comma separated string to a number?

To convert a comma separated string to a numeric array:Call the split() method on the string to get an array containing the substrings. Use the map() method to iterate over the array and convert each string to a number. The map method will return a new array containing only numbers.

How can I convert a comma separated string to an array in PHP?

Given a long string separated with comma delimiter. The task is to split the given string with comma delimiter and store the result in an array. Use explode() or preg_split() function to split the string in php with given delimiter.

How do you add comma separated values in a string array in Java?

The simplest way to convert an array to comma separated String is to create a StringBuilder, iterate through the array, and add each element of the array into StringBuilder after appending the comma.


16 Answers

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);
like image 97
I Hate Lazy Avatar answered Sep 24 '22 22:09

I Hate Lazy


Split it on the , character;

var string = "0,1";
var array = string.split(",");
alert(array[0]);
like image 23
Alex K. Avatar answered Sep 23 '22 22:09

Alex K.


This is easily achieved in ES6;

You can convert strings to Arrays with Array.from('string');

Array.from("01")

will console.log

['0', '1']

Which is exactly what you're looking for.

like image 31
Ray Kim Avatar answered Sep 22 '22 22:09

Ray Kim


If the string is already in list format, you can use the JSON.parse:

var a = "['a', 'b', 'c']";
a = a.replace(/'/g, '"');
a = JSON.parse(a);
like image 33
otaviodecampos Avatar answered Sep 23 '22 22:09

otaviodecampos


Convert all type of strings

var array = (new Function("return [" + str+ "];")());



var string = "0,1";

var objectstring = '{Name:"Tshirt", CatGroupName:"Clothes", Gender:"male-female"}, {Name:"Dress", CatGroupName:"Clothes", Gender:"female"}, {Name:"Belt", CatGroupName:"Leather", Gender:"child"}';

var stringArray = (new Function("return [" + string+ "];")());

var objectStringArray = (new Function("return [" + objectstring+ "];")());

JSFiddle https://jsfiddle.net/7ne9L4Lj/1/

Result in console

enter image description here

Some practice doesnt support object strings

- JSON.parse("[" + string + "]"); // throw error

 - string.split(",") 
// unexpected result 
   ["{Name:"Tshirt"", " CatGroupName:"Clothes"", " Gender:"male-female"}", "      {Name:"Dress"", " CatGroupName:"Clothes"", " Gender:"female"}", " {Name:"Belt"",    " CatGroupName:"Leather"", " Gender:"child"}"]
like image 45
Andi AR Avatar answered Sep 23 '22 22:09

Andi AR


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

var listValues = "[{\"ComplianceTaskID\":75305,\"RequirementTypeID\":4,\"MissedRequirement\":\"Initial Photo Upload NRP\",\"TimeOverdueInMinutes\":null}]";

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

This gives you an Array of numbers.

now you variable value is like array.length=1

Value output

array[0].ComplianceTaskID
array[0].RequirementTypeID
array[0].MissedRequirement
array[0].TimeOverdueInMinutes
like image 36
Raghav Chaubey Avatar answered Sep 22 '22 22:09

Raghav Chaubey


You can use split

Reference: http://www.w3schools.com/jsref/jsref_split.asp

"0,1".split(',')

like image 42
dm03514 Avatar answered Sep 25 '22 22:09

dm03514


Another option using the ES6 is using Spread syntax.

var convertedArray = [..."01234"];

var stringToConvert = "012";
var convertedArray  = [...stringToConvert];
console.log(convertedArray);
like image 27
Abhinav Galodha Avatar answered Sep 25 '22 22:09

Abhinav Galodha


use the built-in map function with an anonymous function, like so:

string.split(',').map(function(n) {return Number(n);});

[edit] here's how you would use it

var string = "0,1";
var array = string.split(',').map(function(n) {
    return Number(n);
});
alert( array[0] );
like image 45
Dan Mantyla Avatar answered Sep 24 '22 22:09

Dan Mantyla


How to Convert Comma Separated String into an Array in JavaScript?

var string = 'hello, world, test, test2, rummy, words';
var arr = string.split(', '); // split string on comma space
console.log( arr );
 
//Output
["hello", "world", "test", "test2", "rummy", "words"]

For More Examples of convert string to array in javascript using the below ways:

  1. Split() – No Separator:

  2. Split() – Empty String Separator:

  3. Split() – Separator at Beginning/End:

  4. Regular Expression Separator:

  5. Capturing Parentheses:

  6. Split() with Limit Argument

    check out this link ==> https://www.tutsmake.com/javascript-convert-string-to-array-javascript/

like image 39
Developer Avatar answered Sep 25 '22 22:09

Developer


I remove the characters '[',']' and do an split with ','

let array = stringObject.replace('[','').replace(']','').split(",").map(String);
like image 21
Samuel Ivan Avatar answered Sep 21 '22 22:09

Samuel Ivan


More "Try it Yourself" examples below.

Definition and Usage The split() method is used to split a string into an array of substrings, and returns the new array.

Tip: If an empty string ("") is used as the separator, the string is split between each character.

Note: The split() method does not change the original string.

var res = str.split(",");
like image 42
HAROONMIND Avatar answered Sep 23 '22 22:09

HAROONMIND


You can use javascript Spread Syntax to convert string to an array. In the solution below, I remove the comma then convert the string to an array.

var string = "0,1"
var array = [...string.replace(',', '')]
console.log(array[0])
like image 21
p8ul Avatar answered Sep 23 '22 22:09

p8ul


Regexp

As more powerful alternative to split, you can use match

"0,1".match(/\d+/g)

let a = "0,1".match(/\d+/g)

console.log(a);
like image 45
Kamil Kiełczewski Avatar answered Sep 23 '22 22:09

Kamil Kiełczewski


Split (",") can convert Strings with commas into a String array, here is my code snippet.

    var input ='Hybrid App, Phone-Gap, Apache Cordova, HTML5, JavaScript, BootStrap, JQuery, CSS3, Android Wear API'
    var output = input.split(",");
    console.log(output);

["Hybrid App", " Phone-Gap", " Apache Cordova", " HTML5", " JavaScript", " BootStrap", " JQuery", " CSS3", " Android Wear API"]

like image 24
Hitesh Sahu Avatar answered Sep 23 '22 22:09

Hitesh Sahu


var i = "[{a:1,b:2}]",
    j = i.replace(/([a-zA-Z0-9]+?):/g, '"$1":').replace(/'/g,'"'),
    k = JSON.parse(j);

console.log(k)

// => declaring regular expression

[a-zA-Z0-9] => match all a-z, A-Z, 0-9

(): => group all matched elements

$1 => replacement string refers to the first match group in the regex.

g => global flag

like image 26
KARTHIKEYAN.A Avatar answered Sep 25 '22 22:09

KARTHIKEYAN.A