Regex passes the test site but the code does not work

Asked

Viewed 57 times

0

I created a regex ( d{1,}(. d{2})?$ ) that was to allow values in the format 21 or 21.30. I tested the regex on a website and it worked: inserir a descrição da imagem aqui

I’m making the following code:

const regexMoneyFormat = RegExp('^\d{1,}(\.\d{2})?$');
    console.log('valor convertido pra string', price.toString())
    if (!regexMoneyFormat.test(price.toString())) {
      console.log('resultado do teste', regexMoneyFormat.test(price.toString()))
      throw new AppError('Price format invalid, valid shapes: 0 ou 0.00');
    }

Only that the values in the format I mentioned, such as the value 1 or the value 60.21 are not passing. From the print I saw that the function toString() is converting correctly, but is not going through the regex. inserir a descrição da imagem aqui

Why the code isn’t working?

2 answers

3


The builder of RegExp takes a string, and in strings the character \ must be escaped with another \, getting \\. I mean, it should be like this:

const regexMoneyFormat = RegExp('^\\d+(\\.\\d{2})?$');

Another detail is that I switched the quantifier {1,} for + since both mean "one or more occurrences".


Although you can also use the literal form, delimiting the expression between bars:

const regexMoneyFormat = /^\d+(\.\d{2})?$/;

So it is not necessary to escape and you can use only \.


About regex for monetary values, it is worth taking a look here and here.

1

In accordance with the another answer already scored, you must escape the backslashes in a regular expression built from the constructor since this is a necessity of the strings themselves. And the constructor accepts strings.

Of course, you could use the literal form (as already indicated):

const regex = /^\d+(\.\d{2})?$/;

But if you eventually need to use the constructor and don’t want to escape the string (imagine a regex which has many characters that need to be escaped), one option is to use the String.raw:

const regexStr = String.raw`^\d+(\.\d{2})?$`;
const regex = new RegExp(regexStr);

Or, in a single line:

const regex = new RegExp(String.raw`^\d+(\.\d{2})?$`);

The tag String.raw, for strings template, is extremely useful in situations like this, as it does not process exhaust sequences.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.