如何使用正则表达式货币 [英] How to use regex for currency
问题描述
我需要从一个元素中获取价格并将其添加到另一个元素。
I need to grab a price from one element and add it to another.
我使用的是:
\$\d+(?:\.\d+)?
这似乎适用于 $ 0.50
, $ 1.00
, $ 20.00
, $ 200.00
但我碰到了一堵砖墙 $ 1,000.00
和$ 10,000.00
Which seems to work for $0.50
, $1.00
, $20.00
, $200.00
but I hit a brick wall on $1,000.00
and $10,000.00
(不太可能 $ 10,000.00
将会是使用)。
(Unlikely $10,000.00
will ever be used).
逗号让我失望。
**编辑**
我走了一个小时才回到大堆的答案。在我浏览之前,我想我会澄清而不是回答所有评论:
I went away for an hour to come back to heaps of answers. Before I go through them I thought I'd clarify rather than answering all comments:
使用的平台会自动生成购物车中商品的总价值。它在一个元素中呈现 - 这取决于用户是在添加还是删除项目。
The platform being used auto generates the total value of items in a shopping cart. It gets rendered in a an element - this changes depending on whether a user is adding or removing items.
该值不太可能进入10,000.00,因为产品成本不是那么高。
The value is unlikely to go into 10,000.00 because the product costs are not that high.
我是新手使用正则表达式,它花了我足够长的时间来达到这个目的,因此问题。
I am new to using the regex it took me long enough to get this far, hence the question.
自动生成HTML:
<span vertical="False" quote="False" id="catCartSummary">
<table cellspacing="0" class="cartSummaryTable">
<tbody>
<tr>
<td class="cartSummaryItem">3 item(s), Total: $115.00 <a href="#" class="cartSummaryLink">View Cart</a></td>
</tr>
</tbody>
</table>
</span>
在这种情况下我只需要$ 115.00美元 - 但我需要它才能以1,000.00美元的价格工作
I just need the $ value in this case $115.00 - But I need it to work for $1,000.00
推荐答案
替换非数字
和非点
simbols by ''
,然后应用 parseFloat
:
Replace non-digit
and non-dot
simbols by ''
, then apply parseFloat
:
var currencyValue = parseFloat("$1,000.50".replace(/[^\d\.]/g,''));
console.log( currencyValue ) ; //1000.5
更新:如果您的'HTML自动生成器'生成有效货币字符串,然后
UPDATE: If your 'HTML Auto generator' generates valid currency strings, then
/\$\S+/g
regexp足以提取所有货币:
regexp is enough, for extracting all currencies:
var currencies = $('#cartSummaryItem').text().match(/\$\S+/g); // ["$115.00"]
然后你可以将它们转换成数字来执行数学运算:
Then you could convert them to numbers for performing maths on them:
var currenciesAsNumbers = currencies.map( function(item){
return parseFloat( item.replace(/[^\d\.]/g,'') );
}); // [115]
这篇关于如何使用正则表达式货币的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!