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