If you use the RegExp
class you will not need to use the bars; these serve only to define a direct regular expression, without the use of the class. If when you remove the bars your expression marries other values that you should not marry, your expression is wrong. Since you did not give details about what the other strings were that the result was true, but should be false, I assumed they would be for values with more than 3 letters followed by more than 4 numbers or variants thereof
let regex = new RegExp("[a-zA-Z]{3}[0-9]{4}");
const tests = [
'abc1234',
'ab1234', // falta uma letra
'abc123', // falta um número
'1234abc', // começa com número
'abc12345', // tem um número a mais
'abcd1234', // tem uma letra a mais
];
for (let test of tests) {
console.log(test, regex.test(test));
}
If this is indeed the problem, just correct the expression by adding the characters ^
and $
to set the beginning and end of each value, so to match only values that start with 3 letters followed by 4 numbers and nothing more.
let regex = new RegExp("^[a-zA-Z]{3}[0-9]{4}$");
const tests = [
'abc1234',
'ab1234', // falta uma letra
'abc123', // falta um número
'1234abc', // começa com número
'abc12345', // tem um número a mais
'abcd1234', // tem uma letra a mais
];
for (let test of tests) {
console.log(test, regex.test(test));
}
Using the bars instead of the class would be:
let regex = /^[a-zA-Z]{3}[0-9]{4}$/;
const tests = [
'abc1234',
'ab1234', // falta uma letra
'abc123', // falta um número
'1234abc', // começa com número
'abc12345', // tem um número a mais
'abcd1234', // tem uma letra a mais
];
for (let test of tests) {
console.log(test, regex.test(test));
}
Note that in this case it is preferable to use bar notation because the expression is constant. This leaves the code more performative and more semantic. Prefer to use the class RexExp
only when the expression can vary.