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,4192 gold badges35 silver badges54 bronze badges
asked May 4, 2014 at 6:27
3

2 Answers 2

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 []
});
answered May 4, 2014 at 6:31
Sign up to request clarification or add additional context in comments.

1 Comment

Hi, thanks for your answer. Your first piece of code works perfectly. The new solution doesn´t seem to work, Fiddle: jsfiddle.net/wx4Lm
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,4192 gold badges35 silver badges54 bronze badges
answered May 4, 2014 at 6:43

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.