Home > Enterprise >  How do I use RegEx (in JS) to alter multiple dollar amounts to display two decimal places and commas
How do I use RegEx (in JS) to alter multiple dollar amounts to display two decimal places and commas

Time:04-12

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.

CodePudding user response:

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.

  • Related