Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

189
Visualizações
How do I use RegEx (in JS) to alter multiple dollar amounts to display two decimal places and commas (where required)?

I am using this RegEx statement…

/\((\$.*?)\)/g

…to locate all parenthetical dollar amounts found in a string like this…

"My 3 meals were fairly cheap ($45) but I ended up spending a lot more ($1532.01) than I anticipated."

What RegEx statement would amend the source sentence so that all of the parenthetical amounts were properly formatted to include two decimal places and commas where needed?

"My 3 meals were fairly cheap ($45.00) but I ended up spending a lot more ($1,532.01) than I anticipated."

To clarify, the objective is not to extract the values with the proper formatting (e.g., in an array); it's to change the sentence so that it shows the proper formatting.

about 4 years ago · Santiago Gelvez
1 Respostas
Responde à pergunta

0

You can use

const str = 'My 3 meals were fairly cheap ($45) but I ended up spending a lot more ($1532.01) than I anticipated';
const regex = /\$(\d+(?:\.\d+)?)/g;
console.log( str.replace(regex, (m,g) => '$' + Number(g).toLocaleString('en-US', { minimumFractionDigits: 2 })) )

See the regex demo.

Output:

My 3 meals were fairly cheap ($45.00) but I ended up spending a lot more ($1,532.01) than I anticipated

The \$(\d+(?:\.\d+)?) regex matches a $ and then captures into Group 1 any one or more digits followed with an optional sequence of a . and one or more digits.

In the replacement, a callback arrow function is used to append the modified number to the $ char to form the replacement string.

about 4 years ago · Santiago Gelvez Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda