繁体   English   中英

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

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

我有一个像"['a','b','c']"这样的字符串我怎样才能将它转换为数组?

我试过 JSON.parse 但它在 position 1 处出错。

用这个:

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

它将字符串"['a', 'b', 'c']"转换为数组["a", "b", "c"]

虽然它不安全(您应该首先考虑全部后果),但一个非常明显的解决方案可能是使用eval() 我知道你可以使用沙盒来缓解它,但你应该不惜一切代价避免它。

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


所以,我们能做些什么?

这是一个简单的技巧:

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

但也许您想使用反斜杠保留这些字符。

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

但是使用负面的后视并没有得到广泛的支持。

 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