我正在尝试向不包含货币符号的网页上的多个货币值添加
$
符号。
例如,我希望将
25.00
的格式设置为 $25.00
。另一个例子是我希望将 3,100.00
格式化为 $3,100.00
。
我目前正在 Violentmonkey 浏览器扩展中使用用户脚本来完成此任务。由于某种未知的原因,我当前的用户脚本没有格式化网页上的数字。
我尝试使用正则表达式来解决问题,但尽管执行了我的用户脚本,数字仍然未格式化。
(function() {
'use strict';
// Regex to find numbers with two decimal places
const numberRegex = /\d+(,\d+)*\.\d\d/;
// Find all text nodes (more general than specific elements)
const textNodes = document.evaluate(
"//text()",
document,
null,
XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE,
null
);
for (let i = 0; i < textNodes.snapshotLength; i++) {
const node = textNodes.snapshotItem(i);
const text = node.nodeValue;
// Modify and replace the text content
node.nodeValue = text.replace(numberRegex, (match) => {
// Don't add '$' if it already exists
if (match.startsWith('$')) {
return match;
} else {
return '$' + match.replace(",", ","); // Handle commas if they exist
}
});
}
})();
<p>25.00</p>
<p>3,100.00</p>
<div data-cellname="[object Object]" class="css-12hdbj5 css-nil">0.00</div>
<span data-testid="__global!balance-1a1d49c3-9cb8-4c67-896c-0122ac627f08" data-cellname="__global!balance-1a1d49c3-9cb8-4c67-896c-0122ac627f08" class=" css-1ai95jy">45.14</span>
<span class=" css-bs1bqe">0.00</span>
JavaScript 有一个
Intl
对象,它公开了 NumberFormat
方法。使用此方法,您可以创建一个函数,该函数应该接受要格式化为 $ 的货币。
const money = (amount, currency = 'USD', locale = 'en-US') => {
return Intl.NumberFormat(locale, {
style: 'currency',
currency
}).format(amount);
}
您可以为该函数指定任何您选择的名称。
现在,要将数字格式化为 $,只需调用将数字传递给它的函数:
let number = 25;
console.log(money(25));
// $25.00
有关更多信息,请查看 MDN
上的文档