Answer the question
In order to leave comments, you need to log in
How to store and get an array from js base?
Hello.
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
let mask = ['+', '7', '(', /\d/, /\d/, /\d/, ')', ' ', /\d/, /\d/, /\d/, '-', /\d/, /\d/, '-', /\d/, /\d/] //array
Answer the question
In order to leave comments, you need to log in
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/]
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 questionAsk a Question
731 491 924 answers to any question