Home > OS >  Regex expression not returning anything after adding check for precision in input
Regex expression not returning anything after adding check for precision in input

Time:09-26

im just trying to figure out why my input is not outputting anything after I added the precision check in my regex. It simply will not show anything in the input field after the precision check is added into the regex. I have looked for examples to dynamically render the precision value and it seems like it is something similar to what I have implemented in my code:

const handleAssetAmountFormat = (value) => {
    if (value) {
        const precision = transactionType === TRANSACTION_TYPES.BUY ? selectedBaseCurrencyObj.precision.cost : selectedBaseCurrencyObj.precision.amount;
        const regex = new RegExp(`/^\d \.?\d${precision}/`);
        const result = value.match(regex);
        if (result) {
            return result[0];
        }
    }
    return '';
};



const handleAssetAmount = (e) => {
    const { value } = e.target;
    const formattedAmount = handleAssetAmountFormat(value);
    setFromCurrencyAmount(formattedAmount);
  };

Anyone able to figure out what's going on here? Any help is appreciated. Thanks!

CodePudding user response:

Three things are wrong:

  1. You use a string literal, yet you use slashes, they should not be there.
  2. You should use double escape to escape your control characters.
  3. You should add an extra pair of { } around the precision to act as a quantifier.

This result in this regex, that should work:

const regex = new RegExp(`^\\d \\.?\\d{${precision}}`);

Alternatively you could use String.Raw. Then you don't have to double escape. That would be:

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

CodePudding user response:

I don't know what are you trying to check but as far as I can tell normally a re starts with ^(caret) symbol and ends with an $ symbol but you are using a /(escape) character try using the escape characters outside of parentheses.

  • Related