Home > Net >  How to convert string field array back into an array with javascript
How to convert string field array back into an array with javascript

Time:09-09

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?

CodePudding user response:

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!

CodePudding user response:

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 }

CodePudding user response:

You could try matching the string patterns directly, like this:

var items = "['item1', 'item2', 'item3']";
const array = items.match(/(?<=')[^,].*?(?=')/g);
console.log(array)

  • Related