3

I have this string:

items = "['item1', 'item2']"

i need it to be a javascript array like this:

items = ['item1', 'item2']

i try this and it works:

items.replace("]","").replace("[","").replaceAll("'","").split(",");

and the result I obtained was as expected:

['item1', 'item2']

The question is: can the same be done in a simpler way?

6
  • 7
    easiest way: eval(items) or JSON.parse(items.replace(/'/g, '"')) Commented Apr 29, 2021 at 15:27
  • 1
    Required reading for eval: stackoverflow.com/questions/197769/… Commented Apr 29, 2021 at 15:42
  • 2
    Yeah, don't use eval, but JSON.parse is the way to go for stuff like this. Commented Apr 29, 2021 at 16:35
  • @MartinV please check my solution when you have a chance. It uses a regex expression to make the replacement simpler and then JSON.parse() to interpret the final result as JSON data. Commented Apr 29, 2021 at 18:41
  • @ChrisG eval(items) was the solution!, thank you! Commented Apr 29, 2021 at 20:46

1 Answer 1

2

You can accomplish this very simply using a regex text replacement and JSON.parse():

const items = "['item1', 'item2']";

const array = JSON.parse(items.replace(/'/g, '\"'));

console.log(array);

If you would like to avoid JSON.parse() altogether, we can fine-tune the text replacement and use the .split() method like this:

const items = "['item1', 'item2']";

const array = items.replace(/\[|\]|\s|'/g,'').split(',');

console.log(array);

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks @Brandon McConnell! for your answer. Sorry but "items =" is the variable assignment, I did not specify.
Three examples, and none of them matches OP's actual input data...! :D
@MartinV No worries! That makes this even simpler. I’ll make this change and update my answer shortly.
@MartinV I corrected my solution per your clarification. Please check when you have a chance.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.