0

I'm trying to remove " " from an array inside a string.

var test = "['a']"
var test1 = "['a','b']"

Expected Output:

var test_arr  = ['a']
var test1_arr = ['a','b']

I tried replacing, didn't work

var test_arr = test.replace(/\"/, '');

2 Answers2

0

I see two ways to accomplish that.

  1. JSON.parse('["a","b"]') note that the values need to be in double-quotes.
  2. "['a','b']".replace(/[['\]]/g, '').split(',') note that you need to split after replacing the unwanted chars

Both yield an array containing the original strings.

Andre Nuechter
  • 2,141
  • 11
  • 19
0

You can simply convert the single quotes inside the strings to double quotes first to convert the string to a valid JSON, and then we can use JSON.parse to get the required array like:

var test = "['a']"
var test1 = "['a','b']"

var parseStr = str => JSON.parse(str.replace(/'/g, '"'))
var test_arr  = parseStr(test)
var test1_arr = parseStr(test1)

console.log(test_arr)
console.log(test1_arr)
palaѕн
  • 72,112
  • 17
  • 116
  • 136