0

i have a string as below and i would like to extract the array between the quotes.

mystring = "['str1','str2']"

I tried it with eval and i do not want to use eval in my code. is there any other neat way to do this ?

Ling Vu
  • 4,740
  • 5
  • 24
  • 45
boredbear153
  • 241
  • 3
  • 10

1 Answers1

0
function parseString(string) {
  return string
    .split(",")
    .map((str) => str.replace("[", "").replace("]", "").replaceAll("'", ""));
}

This assumes none of array indexes includes character ",".

Erfan
  • 1,725
  • 1
  • 4
  • 12
  • this works as expected. i will also get the input as "[5,6]". In this case, the expected output is [5,6]. However, with the above function it is ["5","6"]. Do i have to transform it again checking if each element is a number or string ? – boredbear153 Sep 15 '21 at 09:17
  • @boredbear153 Why not simply request valid JSON instead? Either use JSON or build your own custom parser. – Sebastian Simon Sep 15 '21 at 09:18
  • @boredbear153, Yes, I think you need to do that. Also, I think there are quite a few other things that should be considered. Will be a complicated function in the end. – Erfan Sep 15 '21 at 09:22
  • @Erfan Yes. i m considering the answer from the below link https://stackoverflow.com/questions/36038454/parsing-string-as-json-with-single-quotes – boredbear153 Sep 15 '21 at 09:23
  • 1
    @SebastianSimon I will request to provide valid JSOn. Not sure if it is possible in this case, based on the outcome, i need to decide my next step. – boredbear153 Sep 15 '21 at 09:24