[javascript] 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 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?

This question is related to javascript arrays string deserialization

The answer is


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"]


Why don't you do replace , comma and split('') the string like this which will result into ['0', '1'], furthermore, you could wrap the result into parseInt() to transform element into integer type.

it('convert string to array', function () {
  expect('0,1'.replace(',', '').split('')).toEqual(['0','1'])
});

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.


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);

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"}"]

Example using Array.filter:

var str = 'a,b,hi,ma,n,yu';

var strArr = Array.prototype.filter.call(str, eachChar => eachChar !== ',');

Regexp

As more powerful alternative to split, you can use match

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

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

console.log(a);
_x000D_
_x000D_
_x000D_


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(",");

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] );

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/


Another option using the ES6 is using Spread syntax.

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

_x000D_
_x000D_
var stringToConvert = "012";_x000D_
var convertedArray  = [...stringToConvert];_x000D_
console.log(convertedArray);
_x000D_
_x000D_
_x000D_


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])

Split it on the , character;

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

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

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

// => 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


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

let array = stringObject.replace('[','').replace(']','').split(",").map(String);

You can use split

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

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


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to deserialization

JSON to TypeScript class instance? Converting Stream to String and back...what are we missing? Newtonsoft JSON Deserialize Deserialize a JSON array in C# How do I deserialize a complex JSON object in C# .NET? .NET NewtonSoft JSON deserialize map to a different property name jackson deserialization json to java-objects Convert string with commas to array NewtonSoft.Json Serialize and Deserialize class with property of type IEnumerable<ISomeInterface> Right way to write JSON deserializer in Spring or extend it