0

I got a result like this :

const result = [ 'arg', 'arg2', '[opt1, opt2]' ]

How can I check in this array if a string can be a array ('[opt1, opt2]') and formate it in real array ?

Thank you

EDIT :

I explain all problem :

I want create a script :

yarn start arg1 arg2 "[option1, option2]"

I need a array of options but I can have a lot args without restrictions, when I recover the result :

const res = process.argv.slice(2)

How can I find my array of options ?

Dams_al
  • 71
  • 1
  • 10
  • why do you have an array into a string? if you take the array out of the string you can do a type check. [ 'arg', 'arg2', ['opt1', 'opt2'] ] – G.Vitelli Oct 22 '20 at 08:49
  • 1
    even if you evaluate the string to an array you will get an reference error because `opt1` isnt defined. Or is this also an string? – bill.gates Oct 22 '20 at 08:50
  • 1
    If the string-array is not json or other known format, you may need to build your own parser. – Eriks Klotins Oct 22 '20 at 08:51
  • does this link below help: [Format String Into Array](https://stackoverflow.com/questions/13272406/convert-string-with-commas-to-array) – Yazan Oct 22 '20 at 08:52
  • please check the update in my answer. It should work – DevCl9 Oct 22 '20 at 09:22

1 Answers1

1

You can try the following solution with string manipulation

const result = ['arg', 'arg2', "[option1, option2]"]

const output = result.map(item => {
  if (/^\[.+\]$/.test(item)) {
    const prepared = item
      .replace('[', '["')
      .replace(']', '"]')
      .replace(/([a-zA-Z0-9]+),+\s+/g, '$1", "')
    return JSON.parse(prepared)
  }
  return item
})

console.log(output)

Explanation:

  • /^\[.+\]$/ regex - checks whether the element is an array (based on the presence of matching square brackets)
  • all other replace statements change the string into valid string encoded JSON array.

Since the overall result is a valid string encoded JSON array, just use JSON.parse after that and return it.

DevCl9
  • 298
  • 1
  • 9