[英]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']
.在 python 中存在 ast.literal_eval(x) ,如果 x 是
"['a','b','c']"
那么它将返回列表['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? Javascript / jQuery 中是否存在类似的东西,我可以将存储在表格单元格中的数组作为 [x,y,z] 并将其转换为文字 JavaScript 数组?
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. ['la maison', "l'animal"]
是一个遇到错误的例子,因为替换单引号或双引号可能会导致问题,因为无法保证它会是哪个。
One could leverage String.prototype.replace()
and JSON.parse()
.可以利用
String.prototype.replace()
和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()
可能更合适。
// 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.但是,由于安全/速度缺陷,MDN 文档不鼓励使用
eval()
。
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.
In JavaScript you can use eval() Function like the sample bellows :在 JavaScript 中,您可以使用 eval() 函数,如下所示:
// 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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.