如何获取给定货币字符串(“GBP”、“USD”等)的货币符号?我想出的最好的方法似乎冗长得可笑,还有其他方法还是我最好使用查找表?
const userLocale = "EN-gb";
const userCurrency = "GBP";
const withValueEl = document.querySelector(".withValue");
const withoutValueEl = document.querySelector(".withoutValue");
const valueWithCurrency = Number(0).toLocaleString(userLocale, {
style: "currency",
currency: userCurrency,
minimumFractionDigits: 2
});
const valueWithoutCurrency = valueWithCurrency.replace(Number(0).toLocaleString(userLocale, {
minimumFractionDigits: 2
}), "")
withValueEl.innerHTML = valueWithCurrency
withoutValueEl.innerHTML = valueWithoutCurrency
With value:<span class="withValue"></span><br /> Without value:<span class="withoutValue"></span><br />
最佳答案
当您包含所有 DOM 选择器和值注入(inject)逻辑(与您想要的功能无关)时,这看起来比实际要做的工作更多。提取符号非常简单:
const getCurrencySymbol = (locale, currency) => (0).toLocaleString(locale, { style: 'currency', currency, minimumFractionDigits: 0, maximumFractionDigits: 0 }).replace(/\d/g, '').trim()
或者如果您不使用 es6:
function getCurrencySymbol (locale, currency) {
return (0).toLocaleString(
locale,
{
style: 'currency',
currency: currency,
minimumFractionDigits: 0,
maximumFractionDigits: 0
}
).replace(/\d/g, '').trim()
}
toLocaleString
选项很详细,因此没有太多可做的。但您不需要使用 Number
构造函数(确实如此)。如果您获得的货币值不带小数点或分隔符,则可以轻松删除数字并仅保留符号。您需要采用这种方法,因为根据区域设置和货币,符号并不总是单个字符。例如:
getCurrencySymbol('en-US', 'CNY') // CN¥
getCurrencySymbol('zh-CN', 'CNY') // ¥
trim 结果也是一个好主意。您可以像示例中那样将 .trim()
链接到结果,或者更新正则表达式以包含空格。
应该注意的是,这是一种有点幼稚的方法,因为它仅适用于数字字符 0-9。如果您需要包含其他数字字符,例如阿拉伯语 (٠١٢٣٤٥٦٧٨٩),则需要更新正则表达式以包括 unicode 范围:/[0-9\u0660-\u0669]/g
。您必须以类似的方式添加需要支持的任何其他数字系统。
本地化是一个不平凡的问题,因此仅使用货币代码来符号 map (如this one)可能更有意义。 .
关于javascript - 获取区域设置的货币符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50650503/