如何搜索包含欧元或欧元或其他货币的文本中的所有部分,以将其转换为我选择的其他货币?
即:
答案 0 :(得分:1)
以下是一些示例代码,用于搜索任何货币的文本并转换为目标货币:
var currencies = {
"EUR": ["€", "EUR", "EURO", "EUROS"],
"USD": ["$", "USD", "USDOLLAR", "USDOLLARS"],
"DEM": ["DEM", "DM", "Deutsche Mark"]
};
var rates = {
"EUR": { USD: 1.2613, DEM: 1.96 },
"USD": { EUR: 0.792832792, DEM: 1.54315 },
"DEM": { USD: 0.648121, EUR: 0.51 }
};
function currencyReplacer(number, sourceCurrency, targetCurrency, currencyFormatIndex, currencySeparator) {
var c, i, comma = /,/g;
for (c in currencies) {
if (currencies.hasOwnProperty(c)) {
for (i = 0; i < currencies[c].length; i++) {
if (currencies[c][i] === sourceCurrency) {
console.log(rates[c][targetCurrency], number);
return [Math.round(rates[c][targetCurrency] * number.replace(comma, "."), 2), currencies[targetCurrency][currencyFormatIndex || 0]].join(currencySeparator || "");
}
}
}
}
return m;
}
function replaceCurrencies(text, sourceCurrency, targetCurrency, currencyFormatIndex, currencySeparator) {
var prefixedRegex = new RegExp("(" + currencies[sourceCurrency].join("|") + ")\\s?(\\d+(?:(?:,|.)\\d+)?)", "gi");
var suffixedRegex = new RegExp("(\\d+(?:(?:,|.)\\d+)?)\\s?(" + currencies[sourceCurrency].join("|") + ")", "gi");
return text.replace(prefixedRegex, function(m, currency, number) {
return currencyReplacer(number, currency, targetCurrency, currencyFormatIndex, currencySeparator);
}).replace(suffixedRegex, function(m, number, currency) {
return currencyReplacer(number, currency, targetCurrency, currencyFormatIndex, currencySeparator);
});
}
replaceCurrencies("This function will convert currencies: €50 is less than 100 EUR which is more than 75 €", "EUR", "DEM", 1, " ");
// will output: "This function will convert currencies: 98 DM is less than 196 DM which is more than 147 DM"
这可以解决你的问题吗?
编辑:更新了上面的代码以包含您想要的目标货币DEM,并使正则表达式/替换程序支持前缀和后缀以及sourceCurrency
Edit2:再次更新代码以处理小数
答案 1 :(得分:0)
如果真的使用了货币,就无法在文本中找到。
例如,您如何区分这些:
但我会让你处理这部分。
如果你有你知道的字符串它是一种货币,你可以这样玩:
// Find out what's the currency used
if ( /[$]/.test( str ) ) // Currency is $
else if ( /[€]/.test( str ) ) // Currency is €
// etc. To get the number out of this string, use:
var val = /\d+/.exec( str ); // if "str === 50$", it returns "50"