4

How to convert this string into original array in Javascript?

var str_arr = "["myName","asldkfjs","2342","sbc@lkjsf.com","sdlkfjskldf",410]"

like I want to store it back as original array

var arr = ["myName","asldkfjs","2342","sbc@lkjsf.com","sdlkfjskldf",410];
Umair Jameel
  • 1,573
  • 3
  • 29
  • 54

2 Answers2

4

You have a syntax error in your str_arr.

var str_arr = '["myName","asldkfjs","2342","sbc@lkjsf.com","sdlkfjskldf",410]';
var arr = JSON.parse(str_arr);
manonthemat
  • 6,101
  • 1
  • 24
  • 49
  • does this work? meaning remove double quotes and replace with single? – Neo Dec 16 '16 at 19:31
  • Yes, double quotes and single quotes are the same in JS – Noam Dec 16 '16 at 19:34
  • It's easy to verify this in a browser console or a nodejs repl. The original post using the double quotes to start the string would cause a syntax error, due to an unexpected identifier, which would be the first m, because of the previous double quotes. So you gotta be careful how you initialize a string that has quotes in them. – manonthemat Dec 16 '16 at 19:35
3

You could try parsing it as JSON, because an array is valid JSON (assuming it uses double quotes for the strings).

arr = JSON.parse(str_arr);

Also, as @manonthemat mentioned, you need to either use single quotes to wrap the string literal where you declare str_arr (since it contains double quotes) or you need to escape the double quotes to avoid a syntax error.

Justin Ryder
  • 757
  • 9
  • 17