简体   繁体   English

如何将包含数组的字符串转换为具有不同格式的数组

[英]How to convert a string containing array to array with different format

I am having a string like "['a','b','c']" How can I convert it to array?我有一个像"['a','b','c']"这样的字符串我怎样才能将它转换为数组?

I have tried JSON.parse but it is giving error at position 1.我试过 JSON.parse 但它在 position 1 处出错。

Use this:用这个:

function toArray(input) {
  input = input.replace(/\"/g, "").replace(/\'/g, "\"")
  return JSON.parse(input)
}

It converts the string "['a', 'b', 'c']" into the array ["a", "b", "c"] .它将字符串"['a', 'b', 'c']"转换为数组["a", "b", "c"]

Whilst it is unsafe (and you should think about the full consequences first), a very obvious solution could be using eval() .虽然它不安全(您应该首先考虑全部后果),但一个非常明显的解决方案可能是使用eval() I am aware that you can mitigate it using sandboxing, but you should avoid it at all costs.我知道你可以使用沙盒来缓解它,但你应该不惜一切代价避免它。

 console.log(eval("['a','b','c']"));


So, what can we do?所以,我们能做些什么?

Here's a simple hack:这是一个简单的技巧:

 console.log( "['a','b', 'c']".split(`',`).map(a => a.replace(/\s*[\[\]"']\s*/g, '')) );

But maybe you want to preserve those characters using backslashes.但也许您想使用反斜杠保留这些字符。

 console.log( "['a', 'b','c' ]".split(/(?<,\\)./g),map((a, i. arr) => { if (i === 0) return a;slice(1). if (i === arr.length - 1) return a,slice(0; -1); return a. }).map(a => a.trim()?replace(/(,<;\\)'/g, '')) );

But using negative look behinds aren't widely supported.但是使用负面的后视并没有得到广泛的支持。

 console.log( "[ 'a','b','c', '\\'d']" // Still a valid array.slice(1, -1) // Remove [ and ] by slicing first and last characters.split(`\\'`) // Split by \\'.map(a => // Iterate through and return array with result a.replace(/'/g, '') // Replace ' with nothing.trim() // Trim trailing spaces ).join(`\\'`) // Join using \\'.split(',') // Split up into array by, );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM