I have a string produit
, and I wanna extract from it a bunch of properties like code_barre,qte…
I’ve tried that with ES2018’s solution which is named capture groups:
let produit = "8234507124671 36,000 5,00 7,00 167,40 DH";
let extractRe = /^(?<code_barre>d*)s+(?<qte>d*,d*)s+(?<prix_unitaire>d*,d*)s+(?<remise>d*,d*)s+(?<montant>d*,d*sw*)$/;
console.log(extractRe.exec(produit).groups)
And it works and I get those properties from that string, BUT if that string produit
changed(doesn’t respect the regex pattern), my regex .exec(produit).groups
will fail :/
So to avoid this error, I would use first an if statement to check if the string respect that pattern.
I know I need to use .test
, But the question is
Is there a way to take an adventage of already pattern
extractRe
to convert it into a pattern we could use in.test
regex method?
something like that:
'^(?<code_barre>d*)s+(?<qte>d*,d*)s+(?<prix_unitaire>d*,d*)s+(?<remise>d*,d*)s+(?<montant>d*,d*sw*)$'.replace(/(.*?)/g,'');
//output:
'^s+s+s+s+$'
//expected output:
'd*s+d*,d*s+d*,d*s+d*,d*s+d*,d*sw*'
to Finally, I can run exec
without errors :/
let produit = "8234507124671 36,000 5,00 7,00 167,40 DH";
let extractRe = /^(?<code_barre>d*)s+(?<qte>d*,d*)s+(?<prix_unitaire>d*,d*)s+(?<remise>d*,d*)s+(?<montant>d*,d*sw*)$/;
if(/^d*s+d*,d*s+d*,d*s+d*,d*s+d*,d*sw*$/.test(produit))
console.log(extractRe.exec(produit).groups)