Javascript从字符串中提取数字

我有一堆使用jQuery从html中提取的字符串。

它们看起来像这样:

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

我需要提取数值以计算价格差异。

(所以我≈we

 var productPriceDiff = DKK 100"; 

要不就:

var productPriceDiff = 100";

任何人都可以帮我这样做吗?

谢谢,雅各布

首先,您需要将输入价格从字符串转换为数字。 然后减去。 而且你必须将结果转换回“DKK ###,##”格式。 这两个function应该有所帮助。

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

然后你可以这样做:

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

尝试:

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

编辑:这将获得包括数字,逗号和句点在内的价格。 它不validation数字格式是否正确或数字,句号等是否连续。 如果您可以更精确地确定您所描述的确切数字定义,那将会有所帮助。

还尝试:

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

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