-1

I want to convert array like looking string into array.

for ex:

from string

 var str = "['Asian', 'Japanese', 'Vegetarian Friendly', 'Vegan Options', 'Gluten Free 
   Options']"

to array

['Asian', 'Japanese', 'Vegetarian Friendly', 'Vegan Options', 'Gluten Free Options']

I have tried this with regex

str.match(/'[a-z]*'/gi).map((elm)=>{
    return elm.replace(/'/g,"")
    })

but this is not considering the spaces in between or more than one word.

Please let me know the efficient solution.

4
  • Do you have it inside a larger string? Commented Mar 2, 2019 at 13:28
  • I'm reading this string from an CSV file using PapaParse. and in csv file data is stored like ['Asian', 'Japanese', 'Vegetarian Friendly', 'Vegan Options', 'Gluten Free Options'] in a single cell Commented Mar 2, 2019 at 13:30
  • You can replace all the ' to " and then JSON.parse. But if you have an apostrophe on any of the items, then it won't work Commented Mar 2, 2019 at 13:30
  • Use '[^']*'... Commented Mar 2, 2019 at 13:33

4 Answers 4

4

Replace the single quotes to double quotes, and convert to array with JSON.parse():

var str = "['Asian', 'Japanese', 'Vegetarian Friendly', 'Vegan Options', 'Gluten Free Options ']"

var result = JSON.parse(str.replace(/'/g, '"'))

console.log(result)

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

Comments

1

Just replace all single quotes by double quotes and JSON.parse() it:

let str = "['Asian', 'Japanese', 'Vegetarian Friendly', 'Vegan Options', 'Gluten Free Options']";

str = str.replace(/'/g,'"') // replace all ' by "

let arr = JSON.parse(str) // now that it's valid JSON, parse it

console.log(arr)

Comments

0
var str = "['Asian', 'Japanese', 'Vegetarian Friendly', 'Vegan Options', 'Gluten Free Options ']";
console.log(JSON.parse(str.replace(/'/g, '"')));

Comments

0
str.replace(/[\[\]']+/g,'').split(', ')

Try this. It is working for the string you posted.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.