简体   繁体   中英

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?

I have tried JSON.parse but it is giving error at 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"] .

Whilst it is unsafe (and you should think about the full consequences first), a very obvious solution could be using 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, );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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