Reputation: 83
Im receiving from an API something like this
"['item1', 'item2', 'item3']"
so even though it looks like an array is actually a string. I want to convert that to an array again so I did this.
let pseudoArray = "['item1', 'item2', 'item3']";
let actualArray = pseudoArray.slice(1, -1).split(', ');
And it kinda works I just remove the brackets at the beginning and the end with slice()
and use split
to separate by the comma into an actual array.
But I feel this is not the best way to do it, is there a better, cleaner way to parse this string into an array?
Upvotes: 1
Views: 140
Reputation: 27222
Best way is to first convert this normal string into a JSON string by replacing single quotes ('
) with double quotes ("
) and then convert that JSON string into JSON object by using JSON.parse()
method.
Live Demo :
let str = "['item1', 'item2', 'item3']";
str = str.replace(/'/g, '"');
console.log(JSON.parse(str));
Upvotes: 0
Reputation: 96
You could try matching the string patterns directly, like this:
var items = "['item1', 'item2', 'item3']";
const array = items.match(/(?<=')[^,].*?(?=')/g);
console.log(array)
Upvotes: 1
Reputation: 4780
Just invert the characters '
and "
to get the correct JSON string:
const str = "['item1', 'item2', 'item3']";
const mapping = {"'": '"', '"': "'"};
const jsonStr = str.replaceAll(/[\'\"]/g, (e) => mapping[e]);
const arr = JSON.parse(jsonStr);
console.log(arr);
.as-console-wrapper { max-height: 100% !important; top: 0 }
Upvotes: 0
Reputation: 717
I think the better approach would be replace all single quote with double quotes.
var items = "['item1', 'item2', 'item3']";
items = items.replace(/'/g, '"') //replacing all ' with "
console.log(JSON.parse(items))
Hope it helps!
Upvotes: 0