Trying to extract prices from a string using regex can be tricky, as unexpected issues may arise.
For example, obtaining the following values:
US$1234.56
$12
$12.34usd
$0.56
.56 dollars
and converting them to:
123456
1200
1234
56
56
is necessary for storing them as Numbers
in the database. The intention is to store the values as cents for indexing purposes.
Currently, the extraction is done with this regex:
var justPrice = fullPrice.replace(/[^0-9]/g, "");
Although this method works, it does not address scenarios where there is a leading zero or convert $12
to 1200
instead of just 12
, representing 12 cents.
Considering straightforward regex cannot handle this logic alone, incorporating JavaScript is an acceptable solution. What would be the most effective approach to achieve the desired outcomes?