I took a stab at implementing something along these lines. As others have mentioned, there is a clear pattern in the [currency] for [currency]
which you can easily match. Take a look below, it's fairly well documented.
/**
* Parse an amount with currency "[symbol (optional)][amount][postfix (optional)] [currency (optional)]"
* @param {String} str Currency string e.g. "$100k dollars", "$100million", "100billion euro"
* @return {Array} See below
*/
function parseCurrency(str) {
var match = /([^0-9\.]+)?([0-9\.]+)(\w+)?(?:\s+(\w+))?/.exec(str);
if(!match) throw new Error("Bad currency input: " + str);
var symbol = match[1], // €, $, £
amount = match[2], // 100, 200
factor = match[3], // k, million i.e. 100k, 100million
unit = match[4] // euro, pound
return [symbol, amount, factor, unit];
}
/**
* Takes in a rate in the form of "[currency] for [currency]"
* @param {String} str "[currency] for [currency]"
* @return {Float} Rate float
*/
function parseRate(str) {
// Split and parse the currencies
var currencies = str.split("for").map(function(amount) {
return parseCurrency(amount.trim());
});
// Calculate the rate
// put the "for [currency]" over the "[currency] for"
var base = expandPostfix(currencies[0][1], currencies[0][2]),
exchangeTo = expandPostfix(currencies[1][1], currencies[1][2]);
return base / exchangeTo;
}
/**
* Expand a number postfix
* @param {Number} num
* @param {String} postfix Postfix such as "k", "m", "billion"
* @return {Number} Expanded number
*/
function expandPostfix(num, postfix) {
return num * (({
k : 1000,
m: 1000000,
million: 1000000
})[postfix] || 1);
}
parseRate("1 euro for 3 pound"); // 0.333
parseRate("10000 something for ∫1"); // 10000
parseRate("1200 Something for ∫0.1"); // 12000