-1

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.

2 Answers2

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"].

lxhom
  • 650
  • 4
  • 15
1

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 ,
);
PiggyPlex
  • 631
  • 1
  • 4
  • 15