Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

181
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda