Convert array string to javascript array

In my code, I read the hidden input value, which is actually an array object javascript

<input type="hidden" id="id_num" value="{{array_values}}">

But when I take it using jquery( $('#id_num").val()) its array string,

"['item1','item2','item3']"

therefore, I cannot repeat it. How do I convert to an array object javascriptso that I can iterate over the elements in the array?

+4
source share
5 answers

You can use JSON.parse, but first you need to replace everything 'with ", since they 'are invalid separators in JSON strings.

var str = "['item1','item2','item3']";

str = str.replace(/'/g, '"');

var arr = JSON.parse(str);

console.log(arr);
Run codeHide result

Another approach:

Using sliceand splitas follows:

var str = "['item1','item2','item3']";

var arr = str.slice(1, -1)                // remove [ and ]
             .split(',')                  // this could cause trouble if the strings contain commas
             .map(s => s.slice(1, -1));   // remove ' and '

console.log(arr);
Run codeHide result
+4

eval ;

eval("[0,1,2]")

;

[0,1,2]

, , , , , eval

+1

var arr = "['item1','item2','item3']";
var res = arr.replace(/'/g, '"')
console.log(JSON.parse(res));
Run codeHide result
0
source

Possible way to resolve this issue:

substrDelete [..]s first .

Then remove the inner quotation marks, as we will get extra quotes when we string.split

Finally, splitwith ,.

let mystring = "['item1','item2','item3']";
let arr = mystring.substr(1, mystring.length - 2)
  .replace(/'/g, "")
  .split(",")
console.log(arr)
Run codeHide result
0
source

Evaluating a line new Functiondoes the trick for me, like a roar:

var arr = "['item1','item2','item3']";
function strEval(fn) {
  return new Function('return ' + fn)();
}
var res = strEval(arr);
console.log(res);
Run codeHide result
0
source

Source: https://habr.com/ru/post/1674053/


All Articles