I have a requirement where I need to compare two fields that contain a total amount.
One of the fields represents the amount like $1000
(the currency symbol followed by amount. Eg. For US $100
, For UK €100
).
I need to parse the field that can have amounts from different countries. How can I do that using JQuery?
Following is the jQuery I am using currently:
var Amt= parseFloat(total.split('$'));
The split function can take in a regular expression. Since $
sign is a special character it must be escaped with a backslash. For another currency symbol, we use the |
symbol to represent OR.
The split function will return an array and since we're splitting on a currency symbol, the symbol gets converted to an empty string ""
. In this case, filter
will only show strings with a truthy value.
I'm not sure exactly what you are looking for, but I made a snippet that I think will be helpful.
var euroTotal = document.getElementById("euro-cost");
var usTotal = document.getElementById("us-cost");
var peruTotal = document.getElementById("peru-cost");
var euroResult = document.getElementById("euro-result");
var usResult = document.getElementById("us-result");
var peruResult = document.getElementById("peru-result");
// Create a regex with currency symbols. Separate symbols with |
var moneyRegex = /[A-Z]{0,2}\$|€|¥|₩|£|CHF|¢|฿|L|Q|₭|₮|₨|₱|Kč|Ft|Rp|лв|RM|MT|₦|Gs|zł|lei|S\/\./;
euroResult.innerHTML = `Parsed, ${euroTotal.innerHTML} equals: ` +
parseFloat(euroTotal.innerHTML.split(moneyRegex).filter(Boolean));
usResult.innerHTML = `Parsed, ${usTotal.innerHTML} equals: ` +
parseFloat(usTotal.innerHTML.split(moneyRegex).filter(Boolean));
peruResult.innerHTML = `Parsed, ${peruTotal.innerHTML} equals: ` +
parseFloat(peruTotal.innerHTML.split(moneyRegex).filter(Boolean));
<h3>Item Costs</h3>
<p>This item costs <span id="euro-cost">€400</span></p>
<p>This item costs <span id="us-cost">$300</span></p>
<p>This item costs <span id="peru-cost">S/.200</span></p>
<h3>Parsing Currency Values</h3>
<p id="euro-result"></p>
<p id="us-result"></p>
<p id="peru-result"></p>
<p><strong>Feel free to play around with different currencies</strong></p>
You can play around with some other currency symbols, and this function should remove them