Javascript - Regular expression for formatting values in real

Asked

Viewed 410 times

-1

Hello, I am studying regular expressions and trying to make a function to format values. The idea is to receive a value and return it formatted. Example:

  • 400.00 --> 400,00
  • 150000.00 --> 150.000,00
  • 1500.00 --> 1.500,00

The solution I arrived at was this:

priceFormat(value){
    let price = value.toString().split('').reverse().join('').replace('.','')
    price = price.replace(/(\d{2})/, '$1,')
    price = price.replace(/(\d{3}(?!$))/g, '$1.') 
    return price.split('').reverse().join('')
}

I decided to flip the string to format it backwards, it seemed easier. I believe there must be a more interesting way to do this task, using a regex perhaps, some idea?

  • The parametervalue will just get the guy Number or the type may also be passed String? I ask why I want to know if what is passed in the parameter can or cannot be considered that the parameter will always be converted into Number.

  • It may be String, so much so that the first thing I did was convert because it comes as Number

  • It could not only replace (dot) '.' by ',' (comma)?

1 answer

1


I will post an alternative to regex.

Refers to a native javascript function toLocaleString.

const valor = 1542;

const currencyBRL = (value) => {
  const formattedValue = value.toLocaleString(
    'pt-BR', 
    { style: 'currency', currency: 'BRL' }
  );

    return formattedValue;
};

console.log(currencyBRL(valor)) // R$ 1.542,00
  • great, did not know this function, is even better than using regex, thank you very much!

Browser other questions tagged

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