How to extract text from string according to mask in JavaScript?

I am working in a license plate reading app using JavaScript. When I read the plate some additional text tends to be included as below: “280SILRJY2G74BR” I know that the license plate mask is XXXNXNN (X for letters and N for numbers) The number of characters and placement that are added varies with several conditions like image quality, proximity of the camera, state of conservation of the plate, etc So, in the example above, if I apply the given mask the real plate number, RJY2G74 is the part that would satisfy the mask.

After researching the subject and some help I arrived to:
RegExp(/[A-Z]{3}\d{1}[A-Z]{1}\d{2}/.exec(myText)?.[0]);
But it returns: “/(?:)/” and I cannot figure out why.

The syntax should be close to

Regex().exec("string")?.[0]

So

RegExp(/[A-Z]{3}\d{1}[A-Z]{1}\d{2}/).exec(myText)?.[0];

Hope it helps.

1 Like

Let me clarify what you have done here, you wrapped results of calling

/[A-Z]{3}\d{1}[A-Z]{1}\d{2}/.exec(myText)?.[0]

in to RegEx object. Inside you used optional chaining “?.”, then returned 0 index of the results, so that couldnt work.

Just do it this way:

let str = ‘280SILRJY2G74BR’; // store here given string
const regex = /[A-Z]{3}\d{1}[A-Z]{1}\d{2}/;
const [match] = regex.exec(str); // store catched group in match variable;
console.log(match); // check if its working as should :slight_smile:

1 Like