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?
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?
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]
jsfiddle: http://jsfiddle.net/0ac42qs2/1/
var mystring = "[-item1,item2]";
var arr = mystring.replace('\[', "").replace('\]', "").split(',')
alert(arr[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);