A
A
Alexander Pankov2020-05-05 18:12:03
JavaScript
Alexander Pankov, 2020-05-05 18:12:03

How to store and get an array from js base?

Hello.
5eb1824199ea8513453681.jpeg

1) line 1 comes from the base (this is a raw record of an array in js)
2) I take this line and do split (, ) to get an array from the line, but I get line 2 (regulars become a line and my lines such as +7 are wrapped still in quotation marks.)

tell me how I can win this, for one plugin to work on VUE I need to get an array-mask, and the elements of the array can be both strings and regular expressions, all this is stored in the database as a string.

here is the third line in the picture, this is how I need it, those from the 1st line I want to get the 3rd one, but I get the 2nd one.

Those I need to get from the base
is

let rawMask = "['+', '7', '(', /\d/, /\d/, /\d/, ')', ' ', /\d/, /\d/, /\d/, '-', /\d/, /\d/, '-', /\d/, /\d/]" //string

and make it as if we declared in js like this
let mask = ['+', '7', '(', /\d/, /\d/, /\d/, ')', ' ', /\d/, /\d/, /\d/, '-', /\d/, /\d/, '-', /\d/, /\d/] //array


maybe it's worth writing to the database somehow differently?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
Ivan Klimenko, 2020-05-05
@PankovAlxndr

function toStringOrRegExp(s) {
    if (s.startsWith("'") && s.endsWith("'")) {
        return s.slice(1, -1);
    }
    if (s.startsWith("/") && s.endsWith("/")) {
        try {
            const regexp = new RegExp(s.slice(1, -1));
            return regexp; 
        } catch (e) {
            return s;
        }
    }
    return s;
}

const raw = "['+', '7', '(', /\d/, /\d/, /\d/, ')', ' ', /\d/, /\d/, /\d/, '-', /\d/, /\d/, '-', /\d/, /\d/]";
const arr = raw.slice(1, -1).split(', ').map(toStringOrRegExp);

console.log(arr);
// ["+", "7", "(", /d/, /d/, /d/, ")", " ", /d/, /d/, /d/, "-", /d/, /d/, "-", /d/, /d/]

S
Stockholm Syndrome, 2020-05-05
@StockholmSyndrome

as an option

const result = mask.map((s) => 
  s.startsWith('/') && s.endsWith('/') ? new RegExp(s.slice(1, -1)) : s);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question