-4

I have a String like

var str =  "['one','two']"

i want to convert it into a array, what are the possibilities ?

is there a elegant solution than stripping quotes

adiga
  • 34,372
  • 9
  • 61
  • 83
Mohammed Rafeeq
  • 2,586
  • 25
  • 26
  • Use str.split(); – M.Hemant May 02 '19 at 09:32
  • If possible, it's would be worth trying to avoid this situation to begin with (and get the data in a non-string format), rather than trying to rescue it with string parsing. – DBS May 02 '19 at 09:33
  • replace single quotes with double quotes.`JSON.parse("['one','two']".replace(/'/g,'"'))` – Maheer Ali May 02 '19 at 09:33
  • 1
    you could take a [JSON](http://json.org/) compliant string with double quotes inside and simply parse this JSON. – Nina Scholz May 02 '19 at 09:33
  • it will give an array with [0] = "['one' and [1] as 'two']" this is not what i want. Hemant – Mohammed Rafeeq May 02 '19 at 09:33
  • 1
    Possible duplicate of [Convert string in array format to javascript array](https://stackoverflow.com/questions/55504013/convert-string-in-array-format-to-javascript-array) and [Parsing string as JSON with single quotes?](https://stackoverflow.com/questions/36038454) – adiga May 02 '19 at 09:35

1 Answers1

0

You can use the replace() and split() methods:

var str = "['one','two']";
str = str.replace( /[\[\]']+/g, '' );

var strarr = str.split( ',' );
console.log( strarr )
Kavian K.
  • 1,340
  • 1
  • 9
  • 11