admin管理员组

文章数量:1277393

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 plex solutions that might be error prone since it's possible that involve splitting on the ma 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.

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 plex solutions that might be error prone since it's possible that involve splitting on the ma 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.

Share Improve this question edited Feb 8, 2018 at 3:40 Seth Killian asked Feb 8, 2018 at 2:54 Seth KillianSeth Killian 9639 silver badges24 bronze badges 10
  • the question is not clear. Please clearly mention what will be the input & what is the expected out – brk Commented Feb 8, 2018 at 2:55
  • JSON.parse() is probably what you want. – Barmar Commented Feb 8, 2018 at 2:56
  • yeah, JSON.parse won't work where "string literals" use ' instead of " .... eval should work though - but understand how evil eval can be – Jaromanda X Commented Feb 8, 2018 at 2:58
  • @cale_b It won't accept the string he posted, but that's a Python literal, not JSON. – Barmar Commented Feb 8, 2018 at 2:58
  • @JaromandaX He asked for something "similar", I didn't think he meant it had to accept Python literals. JSON is the analogous thing for Javascript. – Barmar Commented Feb 8, 2018 at 2:59
 |  Show 5 more ments

2 Answers 2

Reset to default 9

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 plex 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 ma.
  .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.

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);

本文标签: Convert Javascript string to literal arrayStack Overflow