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
['(', /[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)