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.
- 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
2 Answers
Reset to default 9One 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
版权声明:本文标题:Convert Javascript string to literal array - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741281218a2370017.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论