-1

I need to convert this string to an array:

var mystring = "[-item1,item2]";

This is handed to me as a string. Is there a javascript function that can convert this? If not how would you suggest putting item1 and item2 in an array?

Luke101
  • 63,072
  • 85
  • 231
  • 359

3 Answers3

0

Maybe you can use the split() Method:

I would first remove the first and last character in order to get rid of the "[" and"]"

then:

var str = "-item1,item2";
var res = str.split(",");

The result of res will be an array with the values:

[-item1,item2]
Pablo Estrada
  • 3,182
  • 4
  • 30
  • 74
0

jsfiddle: http://jsfiddle.net/0ac42qs2/1/

    var mystring = "[-item1,item2]";

    var arr = mystring.replace('\[', "").replace('\]', "").split(',')

    alert(arr[0])
masum7
  • 822
  • 6
  • 17
0

If text1 and text2 are not var's but literal's you will need to add quotes.
Use JSON.parse to create objects from strings:

var numbers = '[-1,2]';
var mystring = '["text1","text2"]';
var numbersArr = JSON.parse(numbers);
var stringsArr = JSON.parse(mystring);
console.log(numbersArr);
console.log(stringsArr);

JSFIDDLE.

Amir Popovich
  • 29,350
  • 9
  • 53
  • 99