4

I have the following array:

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

How can I convert it to an array like this:

var array = ['Daniel','Alguien','2009',2014];
Allan Kimmer Jensen
  • 4,114
  • 1
  • 29
  • 50
user3288852
  • 195
  • 1
  • 9
  • Split it into an array by `split("-")` and then regex out the value with regex – Sterling Archer May 04 '14 at 06:30
  • possible duplicate of [Reference - What does this regex mean?](http://stackoverflow.com/questions/22937618/reference-what-does-this-regex-mean) – RobG May 04 '14 at 07:09
  • 1
    Duplicate of [*Regex to get string between curly braces “{I want what's between the curly braces}”*](http://stackoverflow.com/questions/413071/regex-to-get-string-between-curly-braces-i-want-whats-between-the-curly-brace) – RobG May 04 '14 at 07:11

2 Answers2

6

You can do it this way:

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 []
});
Amit Joki
  • 53,955
  • 7
  • 67
  • 89
  • Hi, thanks for your answer. Your first piece of code works perfectly. The new solution doesn´t seem to work, **Fiddle:** http://jsfiddle.net/wx4Lm/ – user3288852 May 04 '14 at 17:27
0

Try to use following code , as you can see the string is split by comma and then using regular expressions the necessary part has been pushed to 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];
Allan Kimmer Jensen
  • 4,114
  • 1
  • 29
  • 50
lampdev
  • 1,102
  • 1
  • 6
  • 15