简体   繁体   English

Javascript从字符串中提取数字

[英]Javascript extracting number from string

I have a bunch of strings extracted from html using jQuery. 我有一堆使用jQuery从html中提取的字符串。

They look like this: 它们看起来像这样:

var productBeforePrice = "DKK 399,95";
var productCurrentPrice = "DKK 299,95";

I need to extract the number values in order to calculate the price difference. 我需要提取数值以计算价格差异。

(So I wend up with ≈ (所以我≈we

var productPriceDiff = DKK 100";

or just: 要不就:

var productPriceDiff = 100"; ) var productPriceDiff = 100";

Can anyone help me do this? 任何人都可以帮我这样做吗?

Thanks, Jakob 谢谢你,雅各布

First you need to convert the input prices from strings to numbers. 首先,您需要将输入价格从字符串转换为数字。 Then subtract. 然后减去。 And you'll have to convert the result back to "DKK ###,##" format. 而且你必须将结果转换回“DKK ###,##”格式。 These two functions should help. 这两个功能应该有所帮助。

var priceAsFloat = function (price) {  
   return parseFloat(price.replace(/\./g, '').replace(/,/g,'.').replace(/[^\d\.]/g,''));
}

var formatPrice = function (price) {  
   return 'DKK ' + price.toString().replace(/\./g,',');
}

Then you can do this: 然后你可以这样做:

var productBeforePrice = "DKK 399,95"; 
var productCurrentPrice = "DKK 299,95";
productPriceDiff = formatPrice(priceAsFloat(productBeforePrice) - priceAsFloat(productCurrentPrice));

try: 尝试:

var productCurrentPrice = productBeforePrice.replace(/[^\d.,]+/,'');

edit: this will get the price including numbers, commas, and periods. 编辑:这将获得包括数字,逗号和句点在内的价格。 it does not verify that the number format is correct or that the numbers, periods, etc are contiguous. 它不验证数字格式是否正确或数字,句号等是否连续。 If you can be more precise in the exact number definitions you expcet, it would help. 如果您可以更精确地确定您所描述的确切数字定义,那将会有所帮助。

尝试:

var productCurrentPrice = productBeforePrice.match(/\d+(,\d+)?/)[0];
var productCurrentPrice = parseInt(productBeforePrice.replace(/[^\d\.]+/,''));

这应该使productCurrentPrice成为您追求的实际数字(如果我正确理解您的问题)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM