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 ?

5
  • 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'] ] Commented Oct 22, 2020 at 8: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? Commented Oct 22, 2020 at 8:50
  • 1
    If the string-array is not json or other known format, you may need to build your own parser. Commented Oct 22, 2020 at 8:51
  • does this link below help: Format String Into Array Commented Oct 22, 2020 at 8:52
  • please check the update in my answer. It should work Commented Oct 22, 2020 at 9:22

1 Answer 1

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.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.