Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Convert text to an array

please help.

The input text is

"['(', /[1-9]/, /\d/, /\d/, /\d/, ')', ' ', /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/, /\d/]"

I want to convert to an array

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

['(', /[1-9]/, /\d/, /\d/, /\d/, /\d/, /\d/, /\d/, ')', ' ' ', /\d/, /\d/, /\d/, /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/, /\d/, /\d/, /\d/]

it does not work, it adds quotes.

The split() method didn’t help, tried the flat() method, but maybe there is something else?

>Solution :

Javascript needs special instructions to handle the two types of string

You need to tell it to remove the ' characters, and to create a regular expression when it sees the / character.

This code should do what you want:

const s = "['(', /[1-9]/, /\d/, /\d/, /\d/, ')', ' ', /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/, /\d/]"

const out = s.slice(1, s.length - 1).split(", ").map(e => {
  if (e.startsWith("'")) {
    return e.slice(1, e.length - 1)
  }
  if (e.startsWith("/")) {
    return new RegExp(e.slice(1, e.length - 1))
  }
  throw new Error("Unexpected first character in element " + e)

})


console.log(out)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading