如何搜索包含 € 或 EUR 或其他货币的文本中的所有部分,以将其转换为我选择的其他货币?
IE:
- 如何隔离 € 或 EUR 或其他货币符号的左侧或右侧数字?
- 如何用更改后的值替换那个数字?
- 如何将此应用于之前或之后具有 € 或 EUR 或其他货币符号的网页的所有数字?
如何搜索包含 € 或 EUR 或其他货币的文本中的所有部分,以将其转换为我选择的其他货币?
IE:
以下是一些示例代码,用于在文本中搜索任何货币并转换为目标货币:
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:再次更新代码以处理十进制数
没有办法在文本中找出是否真的使用了一种货币。
例如,您如何区分这些:
但我会让你处理这部分。
如果你有一个知道它是货币的字符串,你可以这样玩:
// 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"