Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Javascript string to literal array

In python there exists ast.literal_eval(x) where if x is "['a','b','c']" then it will return the list ['a','b','c']. Does something similar exist in Javascript / jQuery where I can take the array that is stored in the table cell as [x,y,z] and turn that into a literal JavaScript array?

I'd prefer to avoid any complex solutions that might be error prone since it's possible that involve splitting on the comma or escaping characters.

Edit: I should have given some better examples:

['la maison', "l'animal"] is an example of one that hits an error because doing a replace of a single or double quote can cause an issue since there's no guarantee on which one it'll be.

like image 929
Seth Killian Avatar asked Feb 08 '18 02:02

Seth Killian


2 Answers

One could leverage String.prototype.replace() and JSON.parse().

See below for a rough example.

// String.prototype.replace() + JSON.parse() Strategy.
const input = "['a','b','c']" // Input.
const array = JSON.parse(input.replace(/'/g, '"')) // Array.
console.log(array) // Proof.

Although, given your update/more complex use case, eval() might be more appropriate.

// eval() Strategy.
const input = `['la maison', "l'animal"]` // Input.
const dangerousarray = eval(input) // Array.
const safearray = eval(`new Array(${input.replace(/^\[|\]$/g, '')})`) 
console.log(dangerousarray) // Proof.
console.log(safearray) // Proof.

However, the MDN docs discourage use of eval() due to security/speed flaws.

As a result, one may opt for an approach similar to the following:

// Heavy Replacement Strategy.
const input = `['la maison', 'l\'animal']` // Input.
const array = input
  .replace(/^\[|\]$/g, '') // Remove leading and ending square brackets ([]).
  .split(',') // Split by comma.
  .map((phrase) => // Iterate over each phrase.
    phrase.trim() // Remove leading and ending whitespace.
    .replace(/"/g, '') // Remove all double quotes (").
    .replace(/^\'|\'$/g, '') // Remove leading and ending single quotes (').
  )
console.log(array) // Proof.
like image 150
Arman Charan Avatar answered Nov 15 '22 02:11

Arman Charan


In JavaScript you can use eval() Function like the sample bellows :

// define the string to evaluate
var str_to_evaluate = 'new Array("Saab", "Volvo", "BMW")';

// retreive the result in a array
var cars = eval(str_to_evaluate);

// print the array
console.log(cars);
like image 35
Korteby Farouk Avatar answered Nov 15 '22 03:11

Korteby Farouk