How to convert a string to an array?

I have the following array:

var mystr = "Name[Daniel],Name2[Alguien],Date[2009],Date[2014]";

How can I convert it to an array as follows:

var array = ['Daniel','Alguien','2009',2014];
+4
source share
2 answers

You can do it as follows:

var mystr = "Name[Daniel],Name2[Alguien],Date[2009],Date[2014]"; 
var array = mystr.match(/\[.+?\]/g).map(function(value){  // searches for values in []
    return value.replace(/[\[\]]/g,""); // removes []
});
+6
source

Try using the following code, as you can see that the string is separated by a comma, and then using regular expressions the necessary part was transferred to a new array

var mystr = "Name[Daniel],Name2[Alguien],Date[2009],Date[2014]";
var array = mystr.split(",");
re = /\[(.*)\]/;
var newArray = [];

for (var i = 0; i < array.length; i++) {
    newArray.push(array[i].match(re)[1]);
}

newArray = ['Daniel', 'Alguien', '2009', 2014];
0
source

Source: https://habr.com/ru/post/1539149/


All Articles