Regular expression of monetary value

Asked

Viewed 632 times

1

Hello I have the following function

function CarregarMascaras() {
    $('[data-mascara=numeroMonetario]').keyup(function () {
    this.value = this.value.replace(/[^0-9]+[^\,]?[^0-9]+/g, '');
    }).on('paste', function () {
    this.value = this.value.replace(/[^0-9]+[^\,]?[^0-9]+/g, '');
    });
}

Her idea is as follows, as you type she checks what’s there and keeps it in a format like: N,N. Where N is any number, but when testing it is accepting numbers of the type N,N,N or N.N.N. I would like this function to accept only numbers of the type: N,N.

  • What is the idea when using replace, is to take out all commas? the first case multiple or the last case multiple?

  • the idea is to accept only a comma and any number amount before and after the comma, but only a comma.

  • And in this case 123456,4567893,46546132 which of the commas should stand?

  • only the first: Ex 123456,456789346546132

1 answer

1


To remove all but the first comma you can do so:

$('[data-mascara="numeroMonetario"]').on('paste keyup', function() {
    this.value = this.value.split(/[^\d,]/).filter(Boolean).join('');
    var parts = this.value.split(',').filter(Boolean);
    if (parts.length > 1) this.value = [parts.shift()].concat(parts.join('')).join(',');
});

Example: https://jsfiddle.net/pet80e7o/1

What does that code do?

  • joins both events to not repeat the code
  • with this.value = this.value.split(/[^\d,]/).filter(Boolean).join(''); I take back anything but numbers and commas
  • with var parts = this.value.split(',').filter(Boolean);; breaks the code into parts separated by commas and cleans empty parts
  • [parts.shift()] keep the first part and remove it from parts
  • parts.join('') joins the other parts without commas
  • .join(','); together the first part with the rest
  • That’s right, man, thank you very much =D

Browser other questions tagged

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