Convert string with commas to array

匿名 (未验证) 提交于 2019-12-03 02:48:02

问题:

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?

回答1:

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


回答2:

Split it on the , character;

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


回答3:

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.



回答4:

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


回答5:

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 


回答6:

Convert all type of strings

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

Why above best practice , cause its accept string and objectstrings

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

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


回答7:

You can use split

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

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



回答8:

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


回答9:

Another option using the ES6 is using Spread syntax.

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

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


回答10:

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



回答11:

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


回答12:

You can also use this array-make open source component that wraps any value with an array.

Examples:

 makeArray(1) // => [1]  makeArray([1]) // => [1]  makeArray(null) // => [] 

One of its 3 tests wraps a string with an array:

makeArray() should wrap an empty string with an array 


回答13:

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



回答14:

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

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


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!